﻿
Option Explicit On
Imports Llama
Imports Plaice
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.Strings
Imports System.Data.OracleClient
Imports System.Data.SqlClient
Imports Telerik.Data
Imports Telerik.WinControls.UI
Imports Telerik.WinControls
Imports Telerik.WinControls.UI.Export
Imports System.ComponentModel
Imports System.Text
Imports Telerik.WinControls.Export
Imports Telerik.WinControls.UI.Export.ExcelML
Imports System.IO
Imports Microsoft.VisualBasic.CompilerServices
Imports Ingr.RAD2D
Imports Microsoft.Office.Interop
Imports System.Reflection
'20210216 delete revision version by time 固定时间格式，不随着系统时间格式的转化而变化
'20220224 增加了DB Clean模块
'20220304 打开图纸修改为Visible， 如果隐藏，save as PDF不会更新Revision的属性
'20220311 增加了刷新管嘴的功能
'202205   增加了Border功能
'20220531 Generate Report时候不关闭Excel以及有相同名称的在后边加1，增加了一列打印图框原点的XY的位置
'Rev 11.0 修改了自动gap的方式
'20230819 加上了一个开图切换readout unit的功能，用于save as dwg时，尺寸不会失真。
'20251108 增加了DbCleaner的调用功能（用于处理constraint Report）
Public Class MainForm

    Private Const SPLITMARK = "@"
    Private Const PathMark = "\"
    Private DBTypePID As String
    Private strConnection As String
    Private strSymbolpath As String
    Public strPlantPath As String
    Private sSymbolName As String
    Public m_DrawingList As New ArrayList
    Public m_DrawingIDList As New ArrayList
    Public ConstDrawingID As String
    'Dim customMenuItem1 As RadMenuItem = New RadMenuItem("Item 1")
    'Dim customMenuItem2 As RadMenuItem = New RadMenuItem("Item 2")
    Public iIndex As Integer
    Public iTotal As Integer
    Public sMsg As String
    Private shortcuts_Renamed As RadShortcutCollection
    Private provider As MyShortcutProvider
    Private registered As Boolean
    Dim displaySets As InteropIDisplaySetinf.ISPDisplaySets
    Dim dispSet As InteropIDisplaySetinf.ISPDisplaySets
    Dim DwgIDs As String
    Public sDeleteRevision As String
    Public sDeleteVersion As String
    Public sSelect As String

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Text = Me.Text + "  Ver:" + System.Windows.Forms.Application.ProductVersion.ToString
        Me.ComboBox_readout_Unit.Text = "mm"
        '避免由于加载图纸导致的窗口出现速度慢，误以为没有点选成功


        Dim sDomain As String

        Dim i As Integer
        Dim oDrawing As LMDrawing
        Dim oDrawings As New LMDrawings
        Dim arrList As New ArrayList
        Dim sPlantName As String
        Dim objOptionSetting As LMOptionSetting



        Dim a As Object
        a = CreateObject("Wscript.Network")
        sDomain = a.userDomain

        'If sDomain <> "SEI" Then
        '    RadMessageBox.Show("请在SEI域环境中运行此工具！")
        '    Me.Close()
        '    Exit Sub
        'End If

        frmWaitingDialog.ShowDialogForWaiting("Please Wait !")
        PGTree.Nodes.Clear()
        DS = New LMADataSource
        oDrawings = New LMDrawings
        sPlantName = DS.ProjectNumber
        m_PlantName = sPlantName  '日志中记录
        oDrawings.Collect(DS)

        For Each oDrawing In oDrawings

            ConstDrawingID = oDrawing.Id  '获取一张图纸的ID用于获取图纸属性
            arrList.Add(oDrawing.Attributes("Path").Value & "#" & oDrawing.Attributes("SP_ID").Value)
        Next
        arrList.Sort()
        Dim oTRoot = New TreeNode
        oTRoot.Tag = sPlantName
        oTRoot.Text = sPlantName
        PGTree.Nodes.Add(oTRoot)
        For i = 0 To arrList.Count - 1
            LoadPIDHierachy(oTRoot, arrList.Item(i), 1)
        Next

        objOptionSetting = DS.GetOptionSetting("681")

        strSymbolpath = GetCatalogExplorerPath(DS, objOptionSetting)  '获取Symbol文件夹的路径后边Label防止和删除功能用到 \\ZspiD\INGRTEST\P&ID Reference Data\Symbols
        strPlantPath = GetPlantPath()
        '***********  创建log文件夹

        objTime = Now
        strTime = Now.ToString '获取时间
        strUser = System.Environment.GetEnvironmentVariable("USERNAME")  '获取用户名

        sLogPath = "C:\Users\" & strUser & "\Desktop\"

        If IO.Directory.Exists(sLogPath & "SEIToollog") Then
            'log文件夹存在
        Else
            IO.Directory.CreateDirectory(sLogPath & "SEIToollog")
        End If

        loaddrawingproperty()

        'AddHandler customMenuItem1.Click, AddressOf Me.CustomMenuItem1_Click
        'AddHandler customMenuItem2.Click, AddressOf Me.CustomMenuItem2_Click

        System.Threading.Thread.Sleep(500) '程序暂停0.5秒，  主窗口load成功，关闭Waiting窗口
        frmWaitingDialog.CloseDialog()


    End Sub

    Public Function GetCatalogExplorerPath(oDataBase As LMADataSource, objOptionSetting As LMOptionSetting) As String
        Dim objFilter As LMAFilter
        Dim objCriterion As LMACriterion
        Dim objOptionSettings As LMOptionSettings

        objFilter = New LMAFilter
        objCriterion = New LMACriterion

        objCriterion.SourceAttributeName = "Name"
        objCriterion.ValueAttribute = "Catalog Explorer root path"
        objCriterion.Operator = "="
        objFilter.ItemType = "OptionSetting"
        objFilter.Criteria.Add(objCriterion)

        objOptionSettings = New LMOptionSettings


        objOptionSettings.Collect(oDataBase, Filter:=objFilter)
        objOptionSetting = objOptionSettings.Nth(1)

        GetCatalogExplorerPath = objOptionSetting.Attributes("Value").Value

        oDataBase = Nothing
        objOptionSetting = Nothing
        objOptionSettings = Nothing
        objFilter = Nothing
        objCriterion = Nothing

    End Function
    Private Sub LoadPIDHierachy(Node As TreeNode, HString As String, k As Integer)
        Dim oChildNode As TreeNode
        Dim sNodeName As String
        Dim bExist As Boolean
        Dim oAddNode As TreeNode
        Dim i As Integer

        For i = 1 To Split(HString, PathMark).Count - 1
            sNodeName = Split(HString, PathMark)(i)
            bExist = False
            For Each oChildNode In Node.Nodes
                If oChildNode.Text = sNodeName Then
                    'LoadPIDHierachy(oChildNode, HString, k + 1)
                    bExist = True
                    Node = oChildNode
                End If

            Next

            If bExist = False Then
                oAddNode = New TreeNode

                If InStr(sNodeName, "#") > 0 Then

                    oAddNode.Text = Strings.Left(sNodeName, InStr(sNodeName, "#") - 5)
                    oAddNode.Tag = sNodeName

                    Node.Nodes.Add(oAddNode)
                    Node = oAddNode
                Else
                    oAddNode.Tag = sNodeName
                    oAddNode.Text = sNodeName

                    Node.Nodes.Add(oAddNode)
                    Node = oAddNode

                End If

            End If
        Next

    End Sub

    Private Sub PGTree_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles PGTree.AfterCheck
        Dim oTreeNode As TreeNode
        Dim bIsChecked As Boolean
        bIsChecked = e.Node.Checked
        For Each oTreeNode In e.Node.Nodes
            oTreeNode.Checked = bIsChecked
        Next
    End Sub
    ''' <summary>
    ''' 遍历drawing对象的属性
    ''' </summary>
    ''' <param name="LLAMAObj"></param>
    ''' <param name="ItemType"></param>
    ''' <returns></returns>
    Public Function LoopItemAtts(LLAMAObj As Llama.LMDrawing, ItemType As String) As ArrayList
        Dim al As ArrayList = New ArrayList
        Dim objAttr As LMAAttribute
        For Each objAttrInLoop As LMAAttribute In LLAMAObj.Attributes
            objAttr = objAttrInLoop
            If objAttrInLoop.Name = "SP_ID" Or objAttrInLoop.Name = "Name" Or objAttrInLoop.Name = "Path" Then
                '排除默认的3个属性列

            Else
                Try
                    If objAttrInLoop.ISPAttribute.Attribution.ISPEnumAtts.Count > 0 _
                        And objAttrInLoop.ISPAttribute.Attribution.ReadOnlyMask = 0 Then  '0是可以修改，3是不行

                        al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                                                  "                                                                                                         |       " +
                                                  objAttr.Name + "@")
                        '代表属性为select list
                    Else
                        'select list,but readonly
                        al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                                                  "                                                                                                         |       " +
                                                  objAttr.Name)
                    End If
                Catch
                    'no select list
                    al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                                              "                                                                                                         |       " +
                                              objAttr.Name)
                End Try


            End If
        Next
        al.Sort()
        Return al
    End Function
    Private Function loaddrawingproperty()
        Dim al As ArrayList = New ArrayList
        DS = New LMADataSource

        '遍历一遍图纸的所有属性
        Dim objDrawingInLoop As LMDrawing
        Try
            objDrawingInLoop = DS.GetDrawing(ConstDrawingID)   '主窗口Load时，获得的某个图纸的ID
            al = LoopItemAtts(objDrawingInLoop, "Drawing")

            al.Add("Last Modified Time" +
                                           "                                                                                                         |       " +
                                           "Last Modified Time")
            al.Sort()   '属性按字母排序

            For i = 0 To al.Count - 1
                CheckListBoxDraPro.Items.Add(al.Item(i))
            Next
            'SortProp(0, CheckListBoxDraPro.Items.Count - 1)

            'DataGridView2.Rows.Add(1)  '固定一行即可
        Catch
            MessageBox.Show("There are no Drawings")
        End Try
        al = Nothing

        objDrawingInLoop = Nothing

    End Function


    Public Sub ReadColumnFromList()
        Dim DisName As String
        Dim ColName As String
        Dim objAttr As LMAAttribute
        Dim DS As New LMADataSource

        DisName = Mid(CheckListBoxDraPro.SelectedItem, 1, InStr(CheckListBoxDraPro.SelectedItem, "|") - 1)   '用于datagridview的属性列的显示名
        ColName = Mid(CheckListBoxDraPro.SelectedItem, InStr(CheckListBoxDraPro.SelectedItem, "|") + 1)       '用于datagridview的属性列的实际名
        'Dim cmbcol As New DataGridViewComboBoxColumn


        If CheckListBoxDraPro.GetItemChecked(CheckListBoxDraPro.SelectedIndex) Then
            '未被选中
            If Mid(ColName, Len(ColName)) = "@" Then
                ColName = Mid(ColName, 1, Len(ColName) - 1)  '去掉@
            End If
            On Error Resume Next    '防止没有增加过的column，被删除时的报错

            RadGvidViewDralist.Columns.Remove(Trim(ColName))

        Else
            If Mid(ColName, Len(ColName)) = "@" Then     '0是可以修改，3是不行 Then
                '代表属性为select list
                ColName = Mid(ColName, 1, Len(ColName) - 1)  '去掉@
                Dim objDrawingInLoop As LMDrawing

                objDrawingInLoop = DS.GetDrawing(ConstDrawingID)   '主窗口Load时，获得的某个图纸的ID

                objAttr = objDrawingInLoop.Attributes(Trim(ColName))

                Dim cmbcol As New DataGridViewComboBoxColumn
                cmbcol.HeaderText = Trim(DisName) '显示名
                cmbcol.Name = Trim(ColName)

                For i = 1 To objAttr.ISPAttribute.Attribution.ISPEnumAtts.Count   '这时候确认是select list了，没必要做判断了
                    cmbcol.Items.Add(objAttr.ISPAttribute.Attribution.ISPEnumAtts.Item(i).Name.ToString)   '每个enum
                Next
                RadGvidViewDralist.Columns.Add(Trim(ColName))

                cmbcol = Nothing


            Else
                '被选中   非select list
                RadGvidViewDralist.Columns.Add(Trim(ColName), Trim(DisName))  '前一个参数是columnName，后一个参数是显示名

            End If

        End If
        RadGvidViewDralist.Refresh()
        'InitializeComponent()
        RadGvidViewDralist.Refresh()
        Me.RadGvidViewDralist.EnableFiltering = True
        Me.RadGvidViewDralist.ShowFilteringRow = False
        Me.RadGvidViewDralist.ShowHeaderCellButtons = True
        Me.RadGvidViewDralist.BestFitColumns()

    End Sub

    ''' <summary>
    ''' 根据选择的属性，更新datagridview的列
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Public Sub CheckListBoxDraPro_CheckChanged(sender As Object, e As EventArgs) Handles CheckListBoxDraPro.ItemCheck
        ReadColumnFromList()
        'LoadDrawing()
    End Sub

    Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click

        LoadDrawing()

    End Sub

    Public Sub LoadDrawing()
        Dim objHistories As LMHistories
        Dim objDrawings As LMDrawings
        Dim objdrawing As LMDrawing
        Dim objAttr As LMAAttribute
        Dim index As Integer
        Dim strAttrName As String
        Dim DS As New LMADataSource
        Dim ReadOnlymask As Integer
        RadGvidViewDralist.Rows.Clear()
        objHistories = New LMHistories
        objDrawings = New LMDrawings
        index = 0
        Dim i As Integer
        SelectedDrawing()  '查询出所有勾选的图纸

        If m_DrawingList.Count > 0 Then

            For i = 0 To m_DrawingIDList.Count - 1

                objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                '默认的3个属性
                RadGvidViewDralist.Rows.Add(m_DrawingIDList.Item(i),
                                             Mid(objdrawing.Attributes("Path").Value, 1, InStrRev(objdrawing.Attributes("Path").Value, "\") - 1),
                                       objdrawing.Attributes("Name").Value
                                      )               '前三列SP_ID, Path ,Name 'path是\A01\U0101\1.pid，这里把最后的\1.pid去了

                RadGvidViewDralist.Rows(index).Cells("SP_ID").ReadOnly = True  '只读 SP_ID

                RadGvidViewDralist.Rows(index).Cells("SP_ID").Style.ForeColor = Color.Gray
                RadGvidViewDralist.Rows(index).Cells("Path").ReadOnly = True  '只读 PATH
                RadGvidViewDralist.Rows(index).Cells("Path").Style.ForeColor = Color.Gray

                For column = 3 To RadGvidViewDralist.Columns.Count - 1  '前3列属性是默认的,index 0~2被占，所以从3开始
                    strAttrName = RadGvidViewDralist.Columns(column).Name        'ColName
                    objAttr = objdrawing.Attributes(strAttrName)  '这里必须搞一个attribute的对象实例，否则下面一句代码中的属性找不着

                    If strAttrName = "SP_AccessedBy" Then
                        RadGvidViewDralist.Rows(index).Cells("SP_AccessedBy").ReadOnly = True  '只读

                        RadGvidViewDralist.Rows(index).Cells("SP_AccessedBy").Style.BackColor = Color.Orange  '背景色
                        RadGvidViewDralist.Rows(0).Cells("SP_AccessedBy").ReadOnly = True  '只读
                        RadGvidViewDralist.Rows(0).Cells("SP_AccessedBy").Style.BackColor = Color.Orange  '背景色
                        Try
                            File.Open(strPlantPath + objdrawing.Attributes("Path").Value, FileMode.Open).Close()   '尝试打开.pid文件，如果打开失败，就说明这个图纸被别人打开着
                        Catch ex As Exception
                            RadGvidViewDralist.Rows(index).Cells(column).Value = objdrawing.Attributes(strAttrName).Value.ToString   '如果被打开，则给值，不如在数据库中，所有图纸的access by只是记录最后一次打开的人，即使图纸没人正在打开
                        End Try
                        RadGvidViewDralist.Rows(index).Cells(column).Value = objdrawing.Attributes(strAttrName).Value.ToString
                    ElseIf strAttrName = "Last Modified Time" Then
                        RadGvidViewDralist.Rows(index).Cells("Last Modified Time").ReadOnly = True  '只读
                        RadGvidViewDralist.Rows(index).Cells("Last Modified Time").Style.BackColor = Color.Orange  '背景色
                        RadGvidViewDralist.Rows(0).Cells("Last Modified Time").ReadOnly = True  '只读
                        RadGvidViewDralist.Rows(0).Cells("Last Modified Time").Style.BackColor = Color.Orange  '背景色
                        objHistories = objdrawing.Histories
                        For Each objhi As LMHistory In objHistories   '也就只会循环一次
                            RadGvidViewDralist.Rows(index).Cells("Last Modified Time").Value = objhi.Attributes.Item("Timestamp").Value   '这个属性不在图纸上，而是在history上
                        Next

                    Else  '其他常规的属性

                        ReadOnlymask = objAttr.ISPAttribute().Attribution.ReadOnlyMask     '0是可以修改，3是不行
                        If ReadOnlymask = 0 Then
                            '可以修改
                        ElseIf ReadOnlymask = 3 Then
                            '不可以修改
                            RadGvidViewDralist.Rows(index).Cells(column).ReadOnly = True  '只读
                            RadGvidViewDralist.Rows(index).Cells(column).Style.BackColor = Color.Orange  '背景色

                        End If
                        RadGvidViewDralist.Rows(index).Cells(column).Value = objdrawing.Attributes(strAttrName).Value.ToString   '查询出的数值，放到对应的单元格
                    End If
                Next
                index = index + 1   '下一行
            Next
        End If

        m_DrawingList = Nothing
        m_DrawingIDList = Nothing
        objDrawings = Nothing
        objDrawings = Nothing
        objHistories = Nothing
    End Sub
    Private Sub SelectedDrawing()
        Dim oNode As TreeNode
        m_DrawingList = New ArrayList
        m_DrawingIDList = New ArrayList

        For Each oNode In PGTree.Nodes
            LoadDwgList(oNode)
        Next
    End Sub

    Private Sub LoadDwgList(Node As TreeNode)
        Dim oNode As TreeNode
        Dim locationmark As Integer

        For Each oNode In Node.Nodes
            If oNode.Tag.IndexOf(".pid") > 0 And oNode.Checked Then
                m_DrawingList.Add(oNode.Text)
                locationmark = InStr(oNode.Tag, "#")
                m_DrawingIDList.Add(Strings.Right(oNode.Tag, Strings.Len(oNode.Tag) - locationmark))

            Else
                LoadDwgList(oNode)
            End If
        Next
    End Sub

    Private Sub btnModifyPro_Click(sender As Object, e As EventArgs) Handles btnModifyPro.Click
        RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
        Dim dr As DialogResult = RadMessageBox.Show("Do you want to import grid view data to SPPID?", "Import Data to SPPID", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
            UpdateModeNew(True, 1)
        End If
    End Sub
    Public Sub UpdateModeNew(IfBatch As Boolean, mystep As Integer)
        Dim DS As New LMADataSource
        Dim objdrawing As LMDrawing
        Dim myRow As Integer = 0
        Dim objDrawingWithSameName As LMDrawing
        Dim strAttrName As String

        Dim ismodifyDrawingNumber As Boolean

        'Dim columnsNeedtoClear As ArrayList = New ArrayList   '用于在统一 更新后,删除在grid2中,批量删除的字眼
        Try
            DS.BeginTransaction()  '类似于AUTOCAD二次开发的事务处理器
            ReadUserAndPs_in_PID()   '获取DBtypePID
            ReadAllDBUserAndPs()
            For j = 0 To RadGvidViewDralist.Rows.Count - 1   '遍历行（即grid1所有图纸数目）

                objdrawing = DS.GetDrawing(RadGvidViewDralist.Rows(j).Cells("SP_ID").Value)   '以SP_ID,来获取图纸

                For column = 3 To RadGvidViewDralist.Columns.Count - 1  '遍历列（即所有已选属性数目）,从默认3列往后开始 
                    strAttrName = RadGvidViewDralist.Columns(column).Name    '以列的名字，获取属性数据库名

                    If RadGvidViewDralist.Rows(j).Cells(column).ReadOnly Then
                        '只读的列不更新
                        'ElseIf Me.DataGridView2.Rows(0).Cells(column).Value = "即将清空" Then
                        '    '这种情况，就默认统一更新
                        '    objdrawing.Attributes(strAttrName).Value = System.DBNull.Value
                        '    columnsNeedtoClear.Add(column)
                        '    '做一个判断，批量删除的工作
                    ElseIf strAttrName = "DrawingNumber" Then
                        'DrawingNumber只能单独更新
                        If objdrawing.Attributes(strAttrName).Value <> RadGvidViewDralist.Rows(myRow).Cells(column).Value Then
                            ismodifyDrawingNumber = True
                            objdrawing.Attributes(strAttrName).Value = RadGvidViewDralist.Rows(myRow).Cells(column).Value
                        End If


                        Try   '这里不会去进行拼接，只是单纯对drawingNumber 进行手动的修改
                            UpdateGlobalDrawing(RadGvidViewDralist.Rows(myRow).Cells(column).Value.ToString, objdrawing.Id, "DrawingNumber")   '默认情况下,通过API,不会更新globalDrawing中的数据
                            UpdateDrawingSite(RadGvidViewDralist.Rows(myRow).Cells(column).Value.ToString, objdrawing.Id, "DrawingNumber")   '默认情况下,通过API,不会更新drawingsite中的数据
                            'UpdateDrawingVersion(RadGvidViewDralist.Rows(myRow).Cells(column).Value.ToString, objdrawing.Id, "DrawingNumber")   '默认情况下,通过API,不会更新drawingsite中的数据
                        Catch ex As Exception
                            Exit Sub
                        End Try

                        'ElseIf Me.DataGridView2.Rows(0).Cells(column).Value Is Nothing Then
                        '    'grid2为nothing时，就默认单独更新
                        '    'objDrawing.Attributes(strAttrName).Value = DataGridView1.Rows(myRow).Cells(column).Value
                        '    xxx(DataGridView1, myRow, column)
                    Else
                        '正常属性

                        If Not IsNothing(RadGvidViewDralist.Rows(myRow).Cells(column).Value) Then


                            objdrawing.Attributes(strAttrName).Value = RadGvidViewDralist.Rows(myRow).Cells(column).Value
                            objdrawing.Commit()
                        Else
                            objdrawing.Attributes(strAttrName).Value = DBNull.Value

                            objdrawing.Commit()
                        End If
                    End If
                Next

                If objdrawing.Attributes("Name").Value <> RadGvidViewDralist.Rows(myRow).Cells("Name").Value Then


                    '这里是独立更新,因为默认的3列属性里,就只有Name是可编辑的
                    '去判断下Name是否为唯一

                    'Name Path .pid文件的更新，单独拿出来，因为还要手动去改Path和.pid文件的名称
                    '因为在API中修改图纸名称后,对应.PID文件的名字不会变,是一个BUG,需要手动去修改
                    '可能因为没有权限啥的失败

                    Dim TempPIDName As String
                    Dim oldname As String
                    TempPIDName = strPlantPath + RadGvidViewDralist.Rows(myRow).Cells("Path").Value + "\" + RadGvidViewDralist.Rows(myRow).Cells("Name").Value + ".pid"
                    oldname = strPlantPath + RadGvidViewDralist.Rows(myRow).Cells("Path").Value + "\" + objdrawing.Attributes("Name").Value + ".pid"
                    If GetFileExists（oldname） = True Then  '如果文件夹下有对应的.pid文件重命名，如果没有，不进行处理
                        Try
                            Rename(strPlantPath + objdrawing.Attributes("Path").Value, TempPIDName)         '去文件夹下改.PID的文件名
                        Catch ex As Exception
                            'Sub_end(Me)
                            MessageBox.Show("Drawing " + objdrawing.Attributes("Name").Value + "Make Sure Drawing have been closed" + ex.Message())
                            Exit Sub
                        End Try
                    End If

                    objdrawing.Attributes("Name").Value = RadGvidViewDralist.Rows(myRow).Cells("Name").Value  '更新Name
                    '不会更新GlobalDrawing这个表里的Name和Number

                    objdrawing.Attributes("Path").Value = RadGvidViewDralist.Rows(myRow).Cells("Path").Value + "\" + RadGvidViewDralist.Rows(myRow).Cells("Name").Value + ".pid"   '更新Path,因为数据库的path是 \A01\U0101\1.pid这样，但是用API查出来的是 \A01\U0101
                    Try
                        UpdateGlobalDrawing(RadGvidViewDralist.Rows(myRow).Cells("Name").Value, objdrawing.Id, "Name")  '更新Global Drawing
                        UpdateDrawingSite(RadGvidViewDralist.Rows(myRow).Cells("Name").Value, objdrawing.Id, "Name")   '更新Drawing Site
                        'UpdateDrawingVersion(adGvidViewDralist.Rows(myRow).Cells("Name").Value, objdrawing.Id, "Name")   '默认情况下,通过API,不会更新drawingsite中的数据
                    Catch
                        Rename(TempPIDName, strPlantPath + objdrawing.Attributes("Path").Value)         '去文件夹下改.PID的文件名
                    End Try
                End If
                objdrawing.Commit()
                myRow = myRow + 1
            Next

            '这里会报错，比如违反不唯一性条例时
            DS.CommitTransaction()

        Catch ex As Exception
            'Sub_end(Me)
            MessageBox.Show(objdrawing.Attributes("Path").Value + "  " + ex.Message())
            Exit Sub
        End Try

        RadMessageBox.SetThemeName(RadGvidViewDralist.ThemeName)
        RadMessageBox.Instance.MinimumSize = New Size(100, 100)

        RadMessageBox.Show("Finish Import!")

        'Sub_end(Me)
        'MessageBox.Show("Done!")

        'For i = 0 To columnsNeedtoClear.Count - 1
        '    DataGridView2.Rows(0).Cells(columnsNeedtoClear(i)).Value = ""   '清空grid2
        'Next
        objDrawingWithSameName = Nothing
        myRow = Nothing

    End Sub
    Private Declare Function PathFileExists Lib "shlwapi.dll" Alias "PathFileExistsA" (ByVal pszPath As String) As Long  '获取网络路径的文件是否存在的函数，封装在Shell32.DLL系统文件里的一个函数，既可以判断本地文件是否bai存在，又可以判断远程电脑上的文件是否存在
    Public Function GetFileExists(ByVal FileName As String) As Boolean
        If FileName = "" Then
            MessageBox.Show("请输入文件名")
            Exit Function
        Else
            GetFileExists = CBool(PathFileExists(FileName))
        End If
    End Function
    'PID APP的schema
    Public Sub UpdateGlobalDrawing(dwgName As String, spid As String, PropName As String)
        Dim DS As New LMADataSource
        If DBTypePID = "ORACLE" Then
            'data source是ORACLE CLIENT网络服务名
            strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + ActivePlantPIDAppUser + ";pwd=" + ActivePlantPIDAppPS

            conn = New OracleConnection(strConnection)
            comm = New OracleCommand("", conn)

            '查询语句，SPIDM为目标数据库的domainschema的名字

            SelectStr = <string>
update t_globaldrawing  
set xxxProp = 'xxxdwgName'
where sp_drawingid = 'xxxID'
            </string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)
            conn.Open()
            comm.CommandText = SelectStr
            comm.ExecuteNonQuery()
            conn.Close()
            Exit Sub
            'TestFailure2:

            conn = Nothing
            comm = Nothing


        Else
            'data source是ORACLE CLIENT网络服务名
            strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantPIDAppUser + ";password=" + ActivePlantPIDAppPS + ";"    '组合起来的连接字符串，帐户验证


            connSql = New SqlConnection(strConnection)
            commSql = New SqlCommand("", connSql)

            '查询语句，SPIDM为目标数据库的domainschema的名字
            SelectStr = <string>
update t_globaldrawing  
set xxxProp = 'xxxdwgName'
where sp_drawingid = 'xxxID'
            </string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)

            connSql.Open()
            commSql.CommandText = SelectStr
            commSql.ExecuteNonQuery()
            connSql.Close()
            Exit Sub
            'TestFailure2:

            connSql = Nothing
            commSql = Nothing
        End If
    End Sub
    'PID PLANT的schema
    Public Sub UpdateDrawingSite(dwgName As String, spid As String, PropName As String)

        Dim DS As New LMADataSource
        If DBTypePID = "ORACLE" Then
            'data source是ORACLE CLIENT网络服务名
            strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + ActivePlantUser + ";pwd=" + ActivePlantPS

            conn = New OracleConnection(strConnection)
            comm = New OracleCommand("", conn)

            '查询语句，SPIDM为目标数据库的domainschema的名字

            SelectStr = <string>update t_DrawingSite  set xxxProp = 'xxxdwgName' where sp_drawingid = 'xxxID'</string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)
            conn.Open()
            comm.CommandText = SelectStr
            comm.ExecuteNonQuery()
            conn.Close()
            Exit Sub
            'TestFailure2:

            conn = Nothing
            comm = Nothing


        Else
            'data source是ORACLE CLIENT网络服务名
            strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantUser + ";password=" + ActivePlantPS + ";"    '组合起来的连接字符串，帐户验证


            connSql = New SqlConnection(strConnection)
            commSql = New SqlCommand("", connSql)

            '查询语句，SPIDM为目标数据库的domainschema的名字
            SelectStr = <string>
update t_DrawingSite  
set xxxProp = 'xxxdwgName'
where sp_drawingid = 'xxxID'
            </string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)

            connSql.Open()
            commSql.CommandText = SelectStr
            commSql.ExecuteNonQuery()
            connSql.Close()
            Exit Sub
            'TestFailure2:

            connSql = Nothing
            commSql = Nothing
        End If
    End Sub
    Public Sub UpdateDrawingVersion(dwgName As String, spid As String, PropName As String)
        Dim DS As New LMADataSource
        If DBTypePID = "ORACLE" Then
            'data source是ORACLE CLIENT网络服务名
            strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + ActivePlantPIDAppUser + ";pwd=" + ActivePlantPIDAppPS

            conn = New OracleConnection(strConnection)
            comm = New OracleCommand("", conn)

            '查询语句，SPIDM为目标数据库的domainschema的名字

            SelectStr = <string>
update T_DRAWINGVERSION  
set xxxProp = 'xxxdwgName'
where sp_drawingid = 'xxxID'
            </string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)
            conn.Open()
            comm.CommandText = SelectStr
            comm.ExecuteNonQuery()
            conn.Close()
            Exit Sub
            'TestFailure2:

            conn = Nothing
            comm = Nothing


        Else
            'data source是ORACLE CLIENT网络服务名
            strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantPIDAppUser + ";password=" + ActivePlantPIDAppPS + ";"    '组合起来的连接字符串，帐户验证


            connSql = New SqlConnection(strConnection)
            commSql = New SqlCommand("", connSql)

            '查询语句，SPIDM为目标数据库的domainschema的名字
            SelectStr = <string>
update t_globaldrawing  
set xxxProp = 'xxxdwgName'
where sp_drawingid = 'xxxID'
            </string>.Value
            SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
            SelectStr = SelectStr.Replace("xxxID", spid)
            SelectStr = SelectStr.Replace("xxxProp", PropName)

            connSql.Open()
            commSql.CommandText = SelectStr
            commSql.ExecuteNonQuery()
            connSql.Close()
            Exit Sub
            'TestFailure2:

            connSql = Nothing
            commSql = Nothing
        End If
    End Sub

    'PID APP的schema
    'Public Sub UpdateGlobalDrawing(PropName As String)

    '    Dim DS As New LMADataSource
    '    If DBTypePID = "ORACLE" Then
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + ActivePlantPIDAppUser + ";pwd=" + ActivePlantPIDAppPS

    '        conn = New OracleConnection(strConnection)
    '        comm = New OracleCommand("", conn)

    '        '查询语句，SPIDM为目标数据库的domainschema的名字


    '        SelectStr = <string>update t_globaldrawing T set xxxProp = 'select D.name  from t_drawing D  where t_globaldrawing.sp_drawingid=D.sp_id'</string>.Value
    '        'SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
    '        'SelectStr = SelectStr.Replace("xxxID", spid)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)
    '        conn.Open()
    '        comm.CommandText = SelectStr
    '        comm.ExecuteNonQuery()
    '        conn.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        conn = Nothing
    '        comm = Nothing


    '    Else
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantPIDAppUser + ";password=" + ActivePlantPIDAppPS + ";"    '组合起来的连接字符串，帐户验证


    '        connSql = New SqlConnection(strConnection)
    '        commSql = New SqlCommand("", connSql)

    '        '查询语句，SPIDM为目标数据库的domainschema的名字
    '        SelectStr = <string>update t_globaldrawing T set xxxProp = 'select D.name  from t_drawing D  where t_globaldrawing.sp_drawingid=D.sp_id'</string>.Value

    '        'SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
    '        'SelectStr = SelectStr.Replace("xxxID", spid)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)

    '        connSql.Open()
    '        commSql.CommandText = SelectStr

    '        commSql.ExecuteNonQuery()

    '        connSql.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        connSql = Nothing
    '        commSql = Nothing
    '    End If
    'End Sub
    'PID PLANT的schema
    'Public Sub UpdateDrawingSite(PropName As String)
    '    Dim DS As New LMADataSource
    '    If DBTypePID = "ORACLE" Then
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + PlantDBSystemUser + ";pwd=" + PlantDBSystemUserPS

    '        conn = New OracleConnection(strConnection)
    '        comm = New OracleCommand("", conn)



    '        '查询语句，SPIDM为目标数据库的domainschema的名字
    '        SelectStr = <string>update ActivePlantUser.t_DrawingSite T Set xxxProp = (select D.name  from ActivePlantPIDAppUser.t_drawing D  where T.sp_drawingid=D.sp_id)</string>.Value

    '        SelectStr = SelectStr.Replace("ActivePlantUser", ActivePlantUser)
    '        SelectStr = SelectStr.Replace("ActivePlantPIDAppUser", ActivePlantPIDAppUser)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)
    '        conn.Open()
    '        comm.CommandText = SelectStr
    '        comm.ExecuteNonQuery()
    '        conn.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        conn = Nothing
    '        comm = Nothing


    '    Else
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantUser + ";password=" + ActivePlantPS + ";"    '组合起来的连接字符串，帐户验证


    '        connSql = New SqlConnection(strConnection)
    '        commSql = New SqlCommand("", connSql)

    '        '查询语句，SPIDM为目标数据库的domainschema的名字
    '        SelectStr = <string>update t_DrawingSite T Set xxxProp = 'select D.name  from t_drawing D  where t_DrawingSite.sp_drawingid=D.sp_id'</string>.Value

    '        'SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
    '        'SelectStr = SelectStr.Replace("xxxID", spid)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)

    '        connSql.Open()
    '        commSql.CommandText = SelectStr
    '        commSql.ExecuteNonQuery()
    '        connSql.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        connSql = Nothing
    '        commSql = Nothing
    '    End If
    'End Sub
    'Public Sub UpdateDrawingVersion(PropName As String)
    '    Dim DS As New LMADataSource
    '    If DBTypePID = "ORACLE" Then
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + ActivePlantPIDAppUser + ";pwd=" + ActivePlantPIDAppPS

    '        conn = New OracleConnection(strConnection)
    '        comm = New OracleCommand("", conn)

    '        '查询语句，SPIDM为目标数据库的domainschema的名字
    '        SelectStr = <string>update T_DRAWINGVERSION T Set xxxProp = 'select D.name  from t_drawing D  where T_DRAWINGVERSION.sp_drawingid=D.sp_id'</string>.Value
    '        'SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
    '        'SelectStr = SelectStr.Replace("xxxID", spid)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)
    '        conn.Open()
    '        comm.CommandText = SelectStr
    '        comm.ExecuteNonQuery()
    '        conn.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        conn = Nothing
    '        comm = Nothing


    '    Else
    '        'data source是ORACLE CLIENT网络服务名
    '        strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + ";user id=" + ActivePlantPIDAppUser + ";password=" + ActivePlantPIDAppPS + ";"    '组合起来的连接字符串，帐户验证


    '        connSql = New SqlConnection(strConnection)
    '        commSql = New SqlCommand("", connSql)

    '        '查询语句，SPIDM为目标数据库的domainschema的名字

    '        SelectStr = <string>update T_DRAWINGVERSION T Set xxxProp = 'select D.name  from t_drawing D  where T_DRAWINGVERSION.sp_drawingid=D.sp_id'</string>.Value

    '        'SelectStr = SelectStr.Replace("xxxdwgName", dwgName)
    '        'SelectStr = SelectStr.Replace("xxxID", spid)
    '        SelectStr = SelectStr.Replace("xxxProp", PropName)

    '        connSql.Open()
    '        commSql.CommandText = SelectStr
    '        commSql.ExecuteNonQuery()
    '        connSql.Close()
    '        Exit Sub
    '        'TestFailure2:

    '        connSql = Nothing
    '        commSql = Nothing
    '    End If
    'End Sub
    Private Function GetPlantPath() As String

        Dim DS As New LMADataSource
        Dim objPlantSettings As New LMPlantSettings
        Dim strPlantPath As String

        objPlantSettings.Collect(DS)

        For Each objPlantSettingInLoop In objPlantSettings

            If objPlantSettingInLoop.Attributes("Name").Value = "Plant Path" Then
                strPlantPath = objPlantSettingInLoop.Attributes("Value").Value

                Exit For
            End If
        Next

        Return strPlantPath

    End Function

    Public Sub ReadUserAndPs_in_PID()
        Dim DS As New LMADataSource
        Site_DBNAME = GetStrFromINI("SITESCHEMA", "SQLSERVER_DBNAME", "Error", DS.SiteNode) 'sql server  才有,因为进入sql server需要dbname + schemaName + tableName
        DBTypePID = GetStrFromINI("SITESCHEMA", "DBTYPE", "Error", DS.SiteNode) 'oracle 或者 sql server
        SiteSchemaUser = GetStrFromINI("SITESCHEMA", "UID", "Error", DS.SiteNode) 'SITE Schema的帐号
        SiteSchemaUserPS = UnPassword(GetStrFromINI("SITESCHEMA", "PWD", "Error", DS.SiteNode)) 'SITE Schema的密码
        DBSystemUser = GetStrFromINI("SITESCHEMA", "DBAUSER", "Error", DS.SiteNode) '数据库管理员的帐号
        DBSystemUserPS = UnPassword(GetStrFromINI("SITESCHEMA", "DBA", "Error", DS.SiteNode)) '数据库管理员的密码
        SiteDictionaryUser = GetStrFromINI("DICTIONARY", "UID", "Error", DS.SiteNode) 'SITE Schema Dictionary的帐号
        SiteDictionaryUserPS = UnPassword(GetStrFromINI("DICTIONARY", "PWD", "Error", DS.SiteNode)) 'SITE Schema Dictionary的密码
        If DBTypePID = "ORACLE" Then

            ActiveSiteServer = GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode)
        Else
            ActiveSiteServer = GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode)
        End If

    End Sub
    '解码

    Public Function UnPassword(PSinINI As String) As String

        If PSinINI.Length < 62 Then
        Else
            Dim StartPosition As Integer = 75 - Asc(Mid(PSinINI, 1, 1)) '转为ascii码？
            Dim TruePS As String = ""
            Dim AllSharps As String = ""
            Dim OneCharp As Boolean = False
            '密码可以有空格，空格对应的暗码刚好就是#，所以还不能通过#的数目去判断
            For j = 0 To 7   '8个字符为一个循环
                For i = 2 + j To PSinINI.Length Step 8
                    If i > 8 * (StartPosition - 1) And OneCharp = False Then
                        i = i - 1
                        OneCharp = True
                    End If
                    AllSharps = AllSharps + Chr(Asc(Mid(PSinINI, i, 1)) - 3)
                Next
                If AllSharps = "        " Then
                    Exit For
                Else
                    TruePS = TruePS + Mid(AllSharps, StartPosition) + Mid(AllSharps, 1, StartPosition - 1)
                End If
                AllSharps = ""
                OneCharp = False
            Next

            UnPassword = Trim(TruePS)
            OneCharp = Nothing
        End If

    End Function

    Public Sub ReadAllDBUserAndPs()
        Dim DS As New LMADataSource

        SelectStr = <string>select t.name,t.description,t.path,t2.username,t2.password,t2.sp_schema_type,t2.Data_base,t2.dbserver,t2.sysuid,t2.syspassword 
from xxxSchemaName.t_rootitem t 
join xxxSchemaName.t_db_data t2 on t.sp_id=t2.sp_rootitemid
where t.plantgrouptypename='Plant' and t2.sp_schema_type in ('SPPID','SPAPLANT','SPPIDDATA_DICTIONARY')
            </string>.Value   'Data_base在Oracle的情况下为空
        '在ReadUserAndPs_in_PID这个sub中，获得
        Call PIDReadDataByDBA(ActiveSiteServer, DBSystemUser, DBSystemUserPS, Site_DBNAME, SiteSchemaUser, SelectStr, dtCreate)   'SITE层级，从t_db_data中，拿剩下的数据库用户名、密码


        For Each FoundRows As DataRow In dtCreate.Select("NAME = '" + DS.ProjectNumber.ToString + "'")
            If DBTypePID = "ORACLE" Then
                Plant_DBNAME = FoundRows("NAME").ToString    '针对一个site下多个plant,要放在for 里面
            Else
                Plant_DBNAME = FoundRows("Data_base").ToString    '针对一个site下多个plant,要放在for 里面
            End If

            If FoundRows(5).ToString = "SPAPLANT" Then
                ActivePlantUser = FoundRows(3)                       '跳过API，去获得激活工厂的数据库用户名
                ActivePlantPS = UnPassword(FoundRows(4))
                ActivePlantServer = FoundRows("dbserver")            '2020 02 17 因为site和plant所在的server可能会不一样
                PlantDBSystemUser = FoundRows("sysuid")
                PlantDBSystemUserPS = UnPassword(FoundRows("syspassword"))
            ElseIf FoundRows(5).ToString = "SPPID" Then
                ActivePlantPIDAppUser = FoundRows(3)                 '跳过API，去获得激活工厂pid的数据库用户名，以便能获得GlobalDrawing的对象
                ActivePlantPIDAppPS = UnPassword(FoundRows(4))
                ActivePlantPIDAppServer = FoundRows("dbserver")
                'app和plant是在一个server上的
            ElseIf FoundRows(5).ToString = "SPPIDDATA_DICTIONARY" Then
                ActivePlantPIDAppRefUser = FoundRows(3)              '跳过API，去获得激活工厂PIdRef的数据库用户名，以便能获得codelist的对象
                ActivePlantPIDAppRefPS = UnPassword(FoundRows(4))
                ActivePlantPIDAppRefServer = FoundRows("dbserver")
            End If
        Next
        'MessageBox.Show(ActivePlantUser + vbNewLine + ActivePlantPS + vbNewLine + ActivePlantPIDAppUser + vbNewLine + ActivePlantPIDAppPS + vbNewLine + ActivePlantPIDAppRefUser + vbNewLine + ActivePlantPIDAppRefPS + vbNewLine)
    End Sub
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="xxxServer"></param>
    ''' <param name="xxxSysName"></param>
    ''' <param name="xxxSysPS"></param>
    ''' <param name="xxxDBName"></param>
    ''' <param name="xxxSchemaName"></param>
    ''' <param name="strSQL"></param>
    ''' <param name="dt">自带reset功能</param>
    ''' <returns></returns>
    Public Function PIDReadDataByDBA(xxxServer As String, xxxSysName As String, xxxSysPS As String, xxxDBName As String, xxxSchemaName As String, strSQL As String, dt As DataTable) As String
        Dim ErrString As String

        strSQL = strSQL.Replace("xxxSchemaName", xxxSchemaName)
        strSQL = strSQL.Replace("xxxnotequal", "<>")                           '直接在查询语句里写<>会被VB。NET误解
        strSQL = strSQL.Replace("xxxbigger", ">")                           '直接在查询语句里写<>会被VB。NET误解
        strSQL = strSQL.Replace("xxxsmaller", "<")                           '直接在查询语句里写<>会被VB。NET误解

        If DBTypePID = "ORACLE" Then
            'data source是ORACLE CLIENT网络服务名
            strConnection = "Data source=" + xxxServer + ";uid=" + xxxSysName + ";pwd=" + xxxSysPS
            Try
                conn = New OracleConnection(strConnection)
                comm = New OracleCommand("", conn)
                Debug.Print(strSQL)
                adp = New OracleDataAdapter(strSQL, conn)

                dt.Reset()
                adp.Fill(dt)
                ErrString = ""
            Catch ex As Exception
                'MessageBox.Show(DBTypePID & "  " & xxxSchemaName & "  数据库连接失败,请重试")
                'MsgBox("有错  " + ex.Message)
                ErrString = "用户（" & xxxSchemaName & "）" & "错误信息:" & ex.Message
            End Try
            conn = Nothing
            comm = Nothing
            adp = Nothing
        Else
            strConnection = "data source=" + xxxServer + ";initial catalog=" + xxxDBName + ";user id=" + xxxSysName + ";password=" + xxxSysPS + ";"    '组合起来的连接字符串，帐户验证
            Try
                connSql = New SqlConnection(strConnection)
                commSql = New SqlCommand("", connSql)

                adpsql = New SqlDataAdapter(strSQL, connSql)

                dt.Reset()
                adpsql.Fill(dt)
                ErrString = ""
            Catch ex As Exception
                'MessageBox.Show(DBTypePID & "  " & xxxSchemaName & "  数据库连接失败,请重试")
                'MsgBox("有错  " + ex.Message)
                ErrString = "用户（" & xxxSchemaName & "）" & "错误信息:" & ex.Message
            End Try
            connSql = Nothing
            commSql = Nothing
            adpsql = Nothing
        End If
        Return ErrString
    End Function
    '系统管理员的schema
    Public Sub PIDUpdateDataByDBA(xxxDBName As String, xxxSchemaName As String, strSQL As String)
        Dim DS As New LMADataSource

        strSQL = strSQL.Replace("xxxSchemaName", xxxSchemaName)
        strSQL = strSQL.Replace("xxxnotequal", "<>")                           '直接在查询语句里写<>会被VB。NET误解
        strSQL = strSQL.Replace("xxxbigger", ">")                           '直接在查询语句里写<>会被VB。NET误解
        strSQL = strSQL.Replace("xxxsmaller", "<")                           '直接在查询语句里写<>会被VB。NET误解

        If DBTypePID = "ORACLE" Then
            'data source是ORACLE CLIENT网络服务名
            strConnection = "Data source=" + GetStrFromINI("SITESCHEMA", "ORACLE_SERVICE", "Error", DS.SiteNode) + ";uid=" + DBSystemUser + ";pwd=" + DBSystemUserPS
            Try
                conn = New OracleConnection(strConnection)
                comm = New OracleCommand("", conn)

                conn.Open()
                comm.CommandText = strSQL
                Debug.Print(strSQL)
                comm.ExecuteNonQuery() '获取DBtypePID
                conn.Close()

            Catch ex As Exception

                MsgBox("有错  " + ex.Message)
            End Try
            conn = Nothing
            comm = Nothing

        Else
            strConnection = "data source=" + GetStrFromINI("SITESCHEMA", "DBSERVER", "Error", DS.SiteNode) + ";initial catalog=" + xxxDBName + ";user id=" + DBSystemUser + ";password=" + DBSystemUserPS + ";"    '组合起来的连接字符串，帐户验证
            Try
                connSql = New SqlConnection(strConnection)
                commSql = New SqlCommand("", connSql)

                connSql.Open()
                commSql.CommandText = strSQL

                commSql.ExecuteNonQuery()
                connSql.Close()


            Catch ex As Exception
                'MessageBox.Show(DBTypePID & "  " & xxxSchemaName & "  数据库连接失败,请重试")
                MsgBox("有错  " + ex.Message)
            End Try
            connSql = Nothing
            commSql = Nothing

        End If
    End Sub

    Public Sub Writelog(msg As String, mode As String)

        Dim obj As Object = New Object
        'ReadAllDBUserAndPs()
        'Call PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreate)   '拿到pid ref folder/保温文件的路径
        Try

            SyncLock (obj)
                'Using file As System.IO.StreamWriter = New System.IO.StreamWriter(logPosition, True)  '若不存在 会 自动 创建一个。但是上级文件夹需要有
                'fileStreamWrite.WriteLine(DateTime.Now.ToLocalTime().ToString())
                fileStreamWrite.WriteLine("OpeningDrawings" & CONNMARK & strUser & CONNMARK & strTime & CONNMARK & msg + System.Environment.NewLine)
                fileStreamWrite.Close()
            End SyncLock

        Catch ex As Exception
            '免得文件夹路径没有而报错
        End Try
        obj = Nothing
    End Sub

    Private Sub RunExportToExcelML(fileName As String, ByRef openExportFile As Boolean)
        Dim excelExporter As New ExportToExcelML(Me.RadGvidViewDralist)

        excelExporter.SheetName = "Data"
        excelExporter.SummariesExportOption = SummariesOption.ExportAll

        Try
            excelExporter.RunExport(fileName)

            RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
            Dim dr As DialogResult = RadMessageBox.Show("The data in the grid was exported successfully. Do you want to open the file?", "Export to Excel", MessageBoxButtons.YesNo, RadMessageIcon.Question)
            If dr = DialogResult.Yes Then
                openExportFile = True
            End If
        Catch ex As IOException
            RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
            RadMessageBox.Show(Me, ex.Message, "I/O Error", MessageBoxButtons.OK, RadMessageIcon.[Error])
        End Try


    End Sub

    Private Sub btnexport_Click(sender As Object, e As EventArgs) Handles btnexport.Click

        SaveFileDialog.Filter = "Excel (*.xls)|*.xls"
        SaveFileDialog.Title = "Excel File"
        'SaveFileDialog.FilterIndex = 2
        SaveFileDialog.RestoreDirectory = True
        SaveFileDialog.FileName = ""
        SaveFileDialog.ValidateNames = True        '文件有效性验证ValidateNames，验证用户输入是否是一个有效的Windows文件名

        'SaveFileDialog.CheckPathExists = True      '验证文件有效性



        If SaveFileDialog.ShowDialog() <> DialogResult.OK Then
            Return
        End If

        If SaveFileDialog.FileName.Equals(String.Empty) Then
            RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
            RadMessageBox.Show("Please enter a file name.")
            Return
        End If

        Dim fileName As String = Me.SaveFileDialog.FileName
        Dim openExportFile As Boolean = False

        RunExportToExcelML(fileName, openExportFile)

        If openExportFile Then
            Try
                System.Diagnostics.Process.Start(fileName)
                'System.Diagnostics.Process.Start("C:\test\2.xls")
            Catch ex As Exception
                Dim message As String = [String].Format("The file cannot be opened on your system." & vbLf & "Error message: {0}", ex.Message)
                RadMessageBox.Show(message, "Open File", MessageBoxButtons.OK, RadMessageIcon.[Error])
            End Try
        End If
    End Sub

    Private Sub RadGvidViewDralist_llMouseDown(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs)


        If e.Button = MouseButtons.Right Then

            If e.ColumnIndex >= 0 Then

                'If RadGvidViewDralist.SelectedCells. = False Then
                '    RadGvidViewDralist.ClearSelection()
                '    RadGvidViewDralist.Rows(e.RowIndex).Selected = True
                'End If

                'If RadGvidViewDralist.SelectedRows.Count = 1 Then
                '    RadGvidViewDralist.CurrentCell = RadGvidViewDralist.Rows(e.RowIndex).Cells(e.ColumnIndex)
                'End If

                ContextMenuStrip.Show(MousePosition.X, MousePosition.Y)
            End If
        End If
    End Sub

    'Private Sub RadGvidViewDralist_ContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs)
    '    For i As Integer = 0 To e.ContextMenu.Items.Count - 1
    '        Dim contextMenuText As String = e.ContextMenu.Items(i).Text

    '        Select Case contextMenuText
    '            Case "Conditional Formatting"
    '                e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
    '                e.ContextMenu.Items(i + 1).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
    '            Case "Hide Column"
    '                e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
    '            Case "Pinned state"
    '                e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
    '            Case "Best Fit"
    '                e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
    '        End Select
    '    Next
    'End Sub



    '开图纸功能
    Private Sub RadbtnOpenDrw_Click(sender As Object, e As EventArgs) Handles RadbtnOpenDrw.Click
        '初始化
        RadProgressBarElement1.Value1 = 0
        RadProgressBarElement1.Value2 = 0

        sMsg = "Opening Drawing "
        RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
        Dim dr As DialogResult = RadMessageBox.Show("将执行开图，以刷新Title Block及自动断线" + vbNewLine + "为加快速度，请先打开P&ID主程序（draft.exe)", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes And RadCheckDisplaySet.CheckState = 0 And BClearDisplaySet.CheckState = 0 Then
#Region "1"
            frmWaitingDialog.ShowDialogForWaiting("Please Wait")
            Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing
            'Dim objdrawing As LMDrawing
            'Dim objDrawings = New LMDrawings
            Dim objHistories = New LMHistories
            Dim i As Integer
            Dim DwgIDs As String = ""
            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0


            SelectedDrawing()  '查询出所有勾选的图纸
            DS = New LMADataSource
            If m_DrawingList.Count > 0 Then

                For i = 0 To m_DrawingIDList.Count - 1

                    objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                    DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
                Next
                DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
                ReadUserAndPs_in_PID()   '获取DBtypePID
                ReadAllDBUserAndPs()

                SelectStr = ""
                SelectStr = <string>
    select t.name
    from xxxSchemaName.t_drawing t
    where t.sp_id in (xxxDWGIDS)
                        </string>.Value
                SelectStr = Replace(SelectStr, "xxxDWGIDS", DwgIDs)

                PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreate)

                'objDrawings.Collect(DS) '不要全部的图纸，只要选中的就行了
                Try
                    'On Error GoTo Failed
                    objPIDAutoApp = CreateObject("pidautomation.Application")
                    objPIDAutoApp.Visible = True   ' modifed 20220304 如果为false的话，save as PDF Title Block不会更新Revision的属性

                Catch
                    MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                    Exit Sub

                End Try
                iTotal = dtCreate.Rows.Count

                'RadProgressBar1.Maximum = dtCreate.Rows.Count
                'RadProgressBar1.Minimum = 0

                Dim isAutoGap As Boolean = True
                Dim isopenSucess As Boolean = True

                For i = 0 To dtCreate.Rows.Count - 1

                    'DrawingOpenCount = DrawingOpenCount + 1
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(dtCreate(i)(0))
                        Try
                            'Gap 自动断线
                            If System.IO.File.Exists("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL") Then
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                            Else
                                MessageBox.Show("找不到C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                Exit Sub
                            End If



                            'objPID2d = objPIDAutoApp.Application.radapplication
                            'AutoGap.GapAll(objPID2d)    '有的图可以，有的图不行。。
                        Catch ex As Exception
                            isAutoGap = False
                        End Try
                        DrawingOpenCount = DrawingOpenCount + 1
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            isopenSucess = False
                            If isAutoGap = False Then
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开,AutoGap失败，但未正常关闭")
                            Else
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error图纸打开,AutoGap成功，但未正常关闭")
                            End If
                        End Try
                        If isAutoGap = True And isopenSucess = True Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开，AutoGap成功,图纸正常关闭")
                        ElseIf isopenSucess = True And isAutoGap = False Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开,AutoGap失败，图纸正常关闭")
                        End If

                        DrawingOpenCount = DrawingOpenCount + 1

                    Catch ex As Exception

                        If objPIDADrawing Is Nothing Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开失败")

                        End If

                    End Try

                    'objPIDADrawing.Save()


                    IntCount = IntCount + 1
                    'RadProgressBar1.Value = IntCount
                    RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, IntCount, iTotal, sMsg, dtCreate(i)(0))
                Next
                'Sub_end(WaitingForm)
            Else
                'Sub_end(WaitingForm)
                RadMessageBox.Show("You didn't select any drawings ,Please Select Drawings !")
                Exit Sub
            End If
            Try
                '    DS.CommitTransaction()
                objPIDAutoApp.Visible = True '可能会报错，但是对结果又没影响
                objPIDAutoApp.Quit()
            Catch
                LogList.Add(“OpeningDrawing“ & CONNMARK & "    PID程序退出失败")
            End Try
            'objPIDAutoApp.Quit()
            'objPIDAutoApp = Nothing
            objPIDADrawing = Nothing
            objdrawing = Nothing
            objdrawings = Nothing
            objHistories = Nothing
            'RadProgressBar1.Value = 0

            Call ExcuteLog(LogList)
            frmWaitingDialog.CloseDialog()
            'RadMessageBox.Show("Open Drawings Finished." + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString)
            Dim redr As DialogResult = RadMessageBox.Show("Open Drawings Finished！" + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
            If redr = DialogResult.Yes Then
                RunCMD("start " & strLogPath)
            End If

            'fileStreamWrite.Close()  '关闭日志
            DrawingOpenCount = Nothing
            AutoGap = Nothing
            objPID2d = Nothing
#End Region
        ElseIf dr = DialogResult.Yes And RadCheckDisplaySet.CheckState = 1 Then 'Apply Display Set

            frmWaitingDialog.ShowDialogForWaiting("Please Wait")
            Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing
            'Dim objdrawing As LMDrawing
            'Dim objDrawings = New LMDrawings
            Dim objHistories = New LMHistories
            Dim i As Integer
            Dim DwgIDs As String = ""
            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0
            SelectedDrawing()  '查询出所有勾选的图纸
            DS = New LMADataSource
            If m_DrawingList.Count > 0 Then

                For i = 0 To m_DrawingIDList.Count - 1

                    objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                    DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
                Next
                DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
                ReadUserAndPs_in_PID()   '获取DBtypePID
                ReadAllDBUserAndPs()

                SelectStr = ""
                SelectStr = <string>
    select t.name
    from xxxSchemaName.t_drawing t
    where t.sp_id in (xxxDWGIDS)
                        </string>.Value
                SelectStr = Replace(SelectStr, "xxxDWGIDS", DwgIDs)

                PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreate)

                'objDrawings.Collect(DS) '不要全部的图纸，只要选中的就行了
                Try
                    'On Error GoTo Failed
                    objPIDAutoApp = CreateObject("pidautomation.Application")
                    objPIDAutoApp.Visible = False

                Catch
                    MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                    Exit Sub

                End Try

                iTotal = dtCreate.Rows.Count
                'RadProgressBar1.Maximum = dtCreate.Rows.Count
                '    RadProgressBar1.Minimum = 0

                Dim isAutoGap As Boolean = True
                Dim isopenSucess As Boolean = True
                Dim isDisplaySet As Boolean = False

                For i = 0 To dtCreate.Rows.Count - 1
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(dtCreate(i)(0))

                        Try
                            'Gap 自动断线
                            'objPID2d = objPIDAutoApp.Application.radapplication
                            'AutoGap.GapAll(objPID2d)    '有的图可以，有的图不行。。

                            'Gap 自动断线
                            If System.IO.File.Exists("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL") Then
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                            Else
                                MessageBox.Show("找不到C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                Exit Sub
                            End If
                        Catch ex As Exception
                            isAutoGap = False
                        End Try
                        DrawingOpenCount = DrawingOpenCount + 1
                        '            objPIDADrawing.Save()
                        Try
                            displaySets = objPIDAutoApp.ActiveDrawing.ViewDisplaySets
                            Try
                                For Each displaySet In displaySets
                                    If displaySet.Name = TXTDisplaySetName.Text Then
                                        objPIDAutoApp.ActiveDrawing.ApplyDisplaySet(dispSet)
                                        isDisplaySet = True
                                    End If
                                Next
                            Catch ex As Exception
                                MessageBox.Show("Can't apply this DisplaySet")
                                Exit Sub
                            End Try

                            'Debug.Print "Display Set '" & dispSet.Name & "' is active."
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            isopenSucess = False
                            If isAutoGap = False Then
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开,AutoGap失败，但未正常关闭")
                            Else
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开,AutoGap成功，但未正常关闭")
                            End If
                        End Try
                        If isAutoGap = True And isopenSucess = True And isDisplaySet = True Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开，AutoGap成功,ApplyDisplaySet 成功，图纸正常关闭")
                        ElseIf isopenSucess = True And isAutoGap = False And isDisplaySet = False Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开,AutoGap失败，ApplyDisplaySet 失败,图纸正常关闭")
                        ElseIf isopenSucess = True And isDisplaySet = False And isAutoGap = True Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开，AutoGap成功,ApplyDisplaySet 失败，图纸正常关闭")
                        End If

                    Catch ex As Exception
                        If objPIDADrawing Is Nothing Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸未能打开")
                        End If

                    End Try
                    IntCount = IntCount + 1
                    'RadProgressBar1.Value = IntCount
                    RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, IntCount, iTotal, sMsg, dtCreate(i)(0))
                Next
                'Sub_end(WaitingForm)
            Else
                'Sub_end(WaitingForm)
                RadMessageBox.Show("You didn't select any drawings ,Please Select Drawings !")
                Exit Sub
            End If
            Try
                '    DS.CommitTransaction()
                objPIDAutoApp.Visible = True '可能会报错，但是对结果又没影响
                objPIDAutoApp.Quit()
            Catch
                LogList.Add(“OpeningDrawing“ & CONNMARK & "    PID程序退出失败")
            End Try

            Call ExcuteLog(LogList)

            'objPIDAutoApp.Quit()
            'objPIDAutoApp = Nothing
            displaySets = Nothing
            dispSet = Nothing
            objPIDADrawing = Nothing
            objdrawing = Nothing
            objdrawings = Nothing
            objHistories = Nothing
            'RadProgressBar1.Value = 0
            'objPIDAutoApp.Quit()

            frmWaitingDialog.CloseDialog()
            'RadMessageBox.Show("Open Drawings Finished." + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString)
            Dim redr As DialogResult = RadMessageBox.Show("Open Drawings Finished！" + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
            If redr = DialogResult.Yes Then
                RunCMD("start " & strLogPath)    '打开log日志
            End If

            DrawingOpenCount = Nothing
            AutoGap = Nothing
            objPID2d = Nothing
        ElseIf dr = DialogResult.Yes And BClearDisplaySet.CheckState = 1 Then

            frmWaitingDialog.ShowDialogForWaiting("Please Wait")
            Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing
            'Dim objdrawing As LMDrawing
            'Dim objDrawings = New LMDrawings
            Dim objHistories = New LMHistories
            Dim i As Integer
            Dim DwgIDs As String = ""
            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0
            SelectedDrawing()  '查询出所有勾选的图纸
            DS = New LMADataSource
            If m_DrawingList.Count > 0 Then

                For i = 0 To m_DrawingIDList.Count - 1

                    objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                    DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
                Next
                DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
                ReadUserAndPs_in_PID()   '获取DBtypePID
                ReadAllDBUserAndPs()

                SelectStr = ""
                SelectStr = <string>
    select t.name
    from xxxSchemaName.t_drawing t
    where t.sp_id in (xxxDWGIDS)
                        </string>.Value
                SelectStr = Replace(SelectStr, "xxxDWGIDS", DwgIDs)

                PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreate)

                'objDrawings.Collect(DS) '不要全部的图纸，只要选中的就行了
                Try
                    'On Error GoTo Failed
                    objPIDAutoApp = CreateObject("pidautomation.Application")
                    objPIDAutoApp.Visible = False

                Catch
                    MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                    Exit Sub

                End Try
                iTotal = dtCreate.Rows.Count

                'RadProgressBar1.Maximum = dtCreate.Rows.Count
                'RadProgressBar1.Minimum = 0

                Dim isAutoGap As Boolean = True
                Dim isopenSucess As Boolean = True

                For i = 0 To dtCreate.Rows.Count - 1

                    'DrawingOpenCount = DrawingOpenCount + 1

                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(dtCreate(i)(0))

                        Try
                            'Gap 自动断线
                            'objPID2d = objPIDAutoApp.Application.radapplication
                            'AutoGap.GapAll(objPID2d)    '有的图可以，有的图不行。。

                            'Gap 自动断线
                            If System.IO.File.Exists("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL") Then
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                objPIDAutoApp.RunMacro("C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                            Else
                                MessageBox.Show("找不到C:\Program Files (x86)\Smartplant\P&ID Workstation\bin\autogapall.DLL")
                                Exit Sub
                            End If
                        Catch ex As Exception
                            isAutoGap = False

                        End Try

                        DrawingOpenCount = DrawingOpenCount + 1
                        '            objPIDADrawing.Save()
                        Try

                            'displaySets = objPIDAutoApp.ActiveDrawing.ViewDisplaySets
                            objPIDAutoApp.ActiveDrawing.ClearDisplaySet()   '清除Display Set 
                            'Debug.Print "Display Set '" & dispSet.Name & "' is active."
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            isopenSucess = False
                            If isAutoGap = False Then
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开,AutoGap失败，但未正常关闭")
                            Else
                                LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error图纸打开,AutoGap成功，但未正常关闭")
                            End If
                        End Try
                        If isAutoGap = True And isopenSucess = True Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开，AutoGap成功,ClearDisplaySet 成功，图纸正常关闭")
                        ElseIf isopenSucess = True And isAutoGap = False Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    图纸打开,AutoGap失败，图纸正常关闭")
                        End If

                    Catch ex As Exception
                        If objPIDADrawing Is Nothing Then
                            LogList.Add(“OpeningDrawing“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开失败")
                        End If

                    End Try
                    IntCount = IntCount + 1
                    'RadProgressBar1.Value = IntCount
                    RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, IntCount, iTotal, sMsg, dtCreate(i)(0))
                Next
                'Sub_end(WaitingForm)
            Else
                'Sub_end(WaitingForm)
                RadMessageBox.Show("You didn't select any drawings ,Please Select Drawings !")
                Exit Sub
            End If
            Try
                '    DS.CommitTransaction()
                objPIDAutoApp.Visible = True '可能会报错，但是对结果又没影响
                objPIDAutoApp.Quit()
            Catch
                LogList.Add(“OpeningDrawing“ & CONNMARK & "    PID程序退出失败")
            End Try

            Call ExcuteLog(LogList)

            'objPIDAutoApp.Quit()
            'objPIDAutoApp = Nothing
            displaySets = Nothing
            dispSet = Nothing
            objPIDADrawing = Nothing
            objdrawing = Nothing
            objdrawings = Nothing
            objHistories = Nothing
            'RadProgressBar1.Value = 0
            'objPIDAutoApp.Quit()

            frmWaitingDialog.CloseDialog()
            'RadMessageBox.Show("Open Drawings Finished." + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString)
            Dim redr As DialogResult = RadMessageBox.Show("Open Drawings Finished!" + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
            If redr = DialogResult.Yes Then
                RunCMD("start " & strLogPath)
            End If

            DrawingOpenCount = Nothing
            AutoGap = Nothing
            objPID2d = Nothing


        End If
    End Sub
    'Public Sub Sub_start(ref_form As Form)

    '    WaitingForm.StartPosition = FormStartPosition.CenterScreen
    '    WaitingForm.BackColor = Color.White

    '    WaitingForm.Show()
    '    WaitingForm.RadWaitingBar1.Show()
    '    WaitingForm.RadWaitingBar1.ShowText.ToString()
    '    WaitingForm.RadWaitingBar1.StartWaiting()
    '    WaitingForm.TopMost = True
    '    'WaitingForm.Select()
    '    'ref_form.Enabled = False

    'End Sub
    '执行结束，弹窗消失 
    'Public Sub Sub_end(ref_form As Form)
    '    WaitingForm.Close()
    'End Sub

    Private Sub RadBtnFixOPC_Click(sender As Object, e As EventArgs) Handles RadBtnFixOPC.Click
        Call ReadUserAndPs_in_PID()   '获取DBtypePID
        Call ReadAllDBUserAndPs()
        If DBTypePID = "ORACLE" Then
            'ORA
            SelectStr = <STRING>
    DECLARE 
            OPCID xxxSchemaName.T_OPC.SP_ID%Type;
            MateID xxxSchemaName.T_OPC.MatingOPCPath%Type;
            CURSOR OPCIDCursor IS SELECT OPC1.SP_ID, Rep2.SP_DrawingID FROM xxxSchemaName.T_OPC OPC1, xxxSchemaName.T_OPC OPC2, xxxSchemaName.T_Representation Rep1, xxxSchemaName.T_Representation Rep2 
            WHERE OPC1.SP_ID=Rep1.SP_ModelItemID AND OPC1.SP_pairedWithID = OPC2.SP_ID AND OPC2.SP_ID=Rep2.SP_ModelItemID AND Rep1.ItemStatus xxxnotequal 4 AND Rep2.ItemStatus xxxnotequal 4 AND OPC1.MatingOPCPath xxxnotequal Rep2.SP_DrawingID;
    BEGIN  
    OPEN OPCIDCursor; 
    LOOP
            FETCH OPCIDCursor INTO OPCID,MateID;  
            EXIT WHEN OPCIDCursor%NOTFOUND;
            Update xxxSchemaName.T_OPC set MatingOPCPath = MateID where SP_ID = OPCID;
            commit;
    End loop;
    CLOSE OPCIDCursor;          
    END;    
            </STRING>.Value
            Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, SelectStr)
        Else
            'SQL   
            'use InstanceName
            SelectStr = <STRING>

DECLARE @OPCID VARCHAR(50);
DECLARE @MateID VARCHAR(50);
DECLARE OPCIDCursor CURSOR for SELECT OPC1.SP_ID, Rep2.SP_DrawingID FROM xxxSchemaName.T_OPC OPC1, xxxSchemaName.T_OPC OPC2, xxxSchemaName.T_Representation Rep1, xxxSchemaName.T_Representation Rep2 WHERE OPC1.SP_ID=Rep1.SP_ModelItemID AND OPC1.SP_pairedWithID = OPC2.SP_ID AND OPC2.SP_ID=Rep2.SP_ModelItemID AND Rep1.ItemStatus xxxnotequal 4 AND Rep2.ItemStatus xxxnotequal 4 AND OPC1.MatingOPCPath xxxnotequal  Rep2.SP_DrawingID;
BEGIN
OPEN OPCIDCursor;
FETCH NEXT FROM OPCIDCursor INTO @OPCID,@MateID;
while @@FETCH_STATUS = 0
BEgin
FETCH NEXT FROM OPCIDCursor INTO @OPCID,@MateID;
Update xxxSchemaName.T_OPC set xxxSchemaName.T_OPC.MatingOPCPath = @MateID where SP_ID = @OPCID;
End;
CLOSE OPCIDCursor;
END;
   
            </STRING>.Value
            Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, SelectStr)
        End If
        LogList.Add("Fixed Moved OPC" & CONNMARK & "    Fixed Success for All Plant!")
        Call ExcuteLog(LogList)
        RadMessageBox.Show("Finish Fixed OPC for All Plant, Please Update Drawings!")
    End Sub

    Private Sub RadBtnrefreshPlantGroup_Click(sender As Object, e As EventArgs) Handles RadBtnrefreshPlantGroup.Click
        '初始化
        RadProgressBarElement1.Value1 = 0
        RadProgressBarElement1.Value2 = 0
        If Not RadRadioBtnUnit.IsChecked And Not RadRadioBtnArea.IsChecked Then
            RadMessageBox.Show("Please Select Plant Group Type !")
        Else

            Call updateobjectPlantGroup()
        End If

    End Sub
    Public Sub updateobjectPlantGroup()


        Dim DS As New LMADataSource
        Dim Checkeditemcount As Integer
        Dim j As Integer = 0
        Dim i As Integer
        Dim m As Integer
        Dim objPlantItem As LMPlantItem
        Dim objitem As LMAItem
        Dim DrawingCount As Integer = 0
        Dim objPlantGroup As LMPlantGroup
        Dim ArrayItemID As ArrayList = Nothing
        Dim sPlantGroupID As String
        Dim ItemID As ArrayList
        Dim sItemID() As String
        Dim Count As Integer = 0
        DS.BeginTransaction()

        'ItemID = New Collection
        Checkeditemcount = RadCheckedItemType.CheckedItems.Count

        SelectedDrawing()  '查询出所有勾选的图纸

        sMsg = "Update Plant Group"

        If m_DrawingList.Count > 0 Then
            ArrayItemID = New ArrayList
            For i = 0 To m_DrawingIDList.Count - 1
                objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                If Checkeditemcount > 0 Then
                    For j = 0 To Checkeditemcount - 1
                        ItemID = New ArrayList
                        ItemID = GetobjitemID(DS, RadCheckedItemType.CheckedItems(j).Text, m_DrawingList.Item(i))
                        If ItemID.Count > 0 Then
                            ArrayItemID.AddRange(ItemID)
                        End If
                        ItemID = Nothing
                    Next
                End If
            Next
        Else

            RadMessageBox.Show("You didn't select any drawings ,Please Select Drawings !")
            Exit Sub
        End If

        If ArrayItemID.Count > 0 Then

            iTotal = ArrayItemID.Count
            'RadProgressBar1.Maximum = ArrayItemID.Count
            'RadProgressBar1.Minimum = 0
            If RadRadioBtnUnit.IsChecked Then
                If Not RadCheckBox.Checked Then
                    For m = 0 To ArrayItemID.Count - 1
                        If IsDBNull(ArrayItemID.Item(m)) = False Then
                            sItemID = Split(ArrayItemID.Item(m), "#")  '获取ID
                            objPlantItem = DS.GetPlantItem(sItemID(0))
                            objitem = objPlantItem.AsLMAItem()

                            If IsDBNull(objitem.Attributes("SP_PlantGroupID")) Then
                                sPlantGroupID = GetPlantGroupID(DS, objPlantItem, "Unit")
                                If Not sPlantGroupID = “” Then

                                    Try
                                        objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                        objitem.Commit()
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                    Catch ex As Exception
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error can't set the Plant group name value Update Failed!")  '如果提交失败，记录到log中
                                    End Try
                                Else
                                    LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error Can't get object Drawing Plant Group name ,Update Failed!")
                                End If
                            End If
                        End If
                        Count = Count + 1
                        'RadProgressBar1.Value = Count  '更新一个对象，PfogressBar增加一个
                        'RadProgressBar1.Visible = True
                        RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, Count, iTotal, sMsg, "")
                        sItemID = Nothing
                    Next
                Else
                    For m = 0 To ArrayItemID.Count - 1
                        If IsDBNull(ArrayItemID.Item(m)) = False Then
                            sItemID = Split(ArrayItemID.Item(m), "#")
                            objPlantItem = DS.GetPlantItem(sItemID(0))
                            objitem = objPlantItem.AsLMAItem()
                            objPlantGroup = DS.GetPlantGroup(objitem.Attributes("SP_PlantGroupID").Value)  '对象属性中填写的Plant Group 
                            sPlantGroupID = GetPlantGroupID(DS, objPlantItem, "Unit") '对象所在图纸的Plant Group
                            If Not sPlantGroupID = "" Then
                                If IsDBNull(objitem.Attributes("SP_PlantGroupID").Value) = False Then   '如果Object属性中PlantGroupname不为空
                                    If Not objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID Then '如果两者的ID不同
                                        If objPlantGroup.Attributes("PlantGroupType").Value = "Unit" Then  '如果Plant GroupType相同，在LOG中列出，不进行处理
                                            LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error Object Plant Group is not consistent with Drawing Plant Group Name, Please Check!")
                                        Else

                                            '如果两者plantGroupType不同，则刷新
                                            Try
                                                objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                                objitem.Commit()
                                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                            Catch ex As Exception
                                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "  Error can't set the Plant group name value Update Failed!")

                                            End Try
                                        End If
                                    End If
                                Else '如果对象属性中Plant Group Name为空，刷新为对象所在图纸的plantGroup
                                    Try
                                        objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                        objitem.Commit()
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                    Catch ex As Exception
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error can't set the Plant group name value Update Failed!") '如果提交属性失败，log中列出

                                    End Try
                                End If
                            Else  '如果获取对象所在图纸的Plant Group为空，log中报出
                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error Can't get object Drawing Plant Group name ,Update Failed!")
                            End If
                        End If
                        Count = Count + 1
                        'RadProgressBar1.Value = Count
                        'RadProgressBar1.Visible = True
                        RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, Count, iTotal, sMsg, "")
                        sItemID = Nothing
                    Next
                End If

            ElseIf RadRadioBtnArea.IsChecked Then
                If Not RadCheckBox.Checked Then
                    For m = 0 To ArrayItemID.Count - 1
                        If IsDBNull(ArrayItemID.Item(m)) = False Then
                            sItemID = Split(ArrayItemID.Item(m), "#")
                            objPlantItem = DS.GetPlantItem(sItemID(0))
                            objitem = objPlantItem.AsLMAItem()
                            If IsDBNull(objitem.Attributes("SP_PlantGroupID")) Then
                                sPlantGroupID = GetPlantGroupID(DS， objPlantItem, "Area")
                                If Not sPlantGroupID = "" Then
                                    Try
                                        objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                        objitem.Commit()
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                    Catch ex As Exception
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "   Error can't set the Plant group name value Update Failed!")
                                    End Try
                                Else
                                    LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error Can't get object Drawing Plant Group name ,Update Failed!")
                                End If

                            End If
                        End If
                        Count = Count + 1
                        RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, Count, iTotal, sMsg, "")
                        'RadProgressBar1.Value = Count
                        'RadProgressBar1.Visible = True
                        sItemID = Nothing
                    Next
                Else
                    For m = 0 To ArrayItemID.Count - 1
                        If IsDBNull(ArrayItemID.Item(m)) = False Then
                            sItemID = Split(ArrayItemID.Item(m), "#")
                            objPlantItem = DS.GetPlantItem(sItemID(0))
                            objitem = objPlantItem.AsLMAItem()
                            objPlantGroup = DS.GetPlantGroup(objitem.Attributes("SP_PlantGroupID").Value)  '对象属性中填写的Plant Group 
                            sPlantGroupID = GetPlantGroupID(DS, objPlantItem, "Area")  '对象所在图纸的Plant Group
                            If Not sPlantGroupID = "" Then
                                If IsDBNull(objitem.Attributes("SP_PlantGroupID").Value) = False Then   '如果Object属性中PlantGroupname不为空
                                    If Not objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID Then '如果两者的ID不同
                                        If objPlantGroup.Attributes("PlantGroupType").Value = "Area" Then  '如果Plant GroupType相同，在LOG中列出，不进行处理
                                            LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "   Error Object Plant Group is not consistent with Drawing Plant Group Name, Please Check！")
                                        Else

                                            '如果两者plantGroupType不同，则刷新
                                            Try
                                                objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                                objitem.Commit()
                                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                            Catch ex As Exception
                                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "  Error can't set the Plant group name value Update Failed!")

                                            End Try
                                        End If
                                    End If
                                Else '如果对象属性中Plant Group Name为空，刷新为对象所在图纸的plantGroup
                                    Try
                                        objitem.Attributes("SP_PlantGroupID").Value = sPlantGroupID
                                        objitem.Commit()
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Update Successfully!")
                                    Catch ex As Exception
                                        LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "   Error can't set the Plant group name value Update Failed!") '如果提交属性失败，log中列出

                                    End Try
                                End If
                            Else  '如果获取对象所在图纸的Plant Group为空，log中报出
                                LogList.Add(“Update Plant Group “ & CONNMARK & sItemID(1) & "    Error Can't get object Drawing Plant Group name ,Update Failed!")
                            End If
                        End If
                        Count = Count + 1
                        'RadProgressBar1.Value = Count
                        'RadProgressBar1.Visible = True
                        RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, Count, iTotal, sMsg, "")
                        sItemID = Nothing
                    Next
                End If
            End If

            objitem = Nothing
            objPlantItem = Nothing
            ArrayItemID = Nothing
            sPlantGroupID = Nothing
        Else

            RadMessageBox.Show("No object need to be update!")
        End If

        DS.CommitTransaction()
        Call ExcuteLog(LogList)
        RadMessageBox.Show("Finish Update !")
        'RadProgressBar1.Value = 0
    End Sub

    Public Function GetPlantGroupID(DS As LMADataSource, oPlantitem As LMPlantItem, PlantGroupType As String） As String
        Dim objplantGroup As LMPlantGroup
        Dim sPlantGroupID As String = ""


        objplantGroup = oPlantitem.Representations.Nth(1).DrawingObject.PlantGroupObject
        If IsDBNull(objplantGroup) = False Then

            If PlantGroupType = "Unit" And objplantGroup.Attributes("PlantGroupType").Value = "Unit" Then
                sPlantGroupID = objplantGroup.Id  '只适用于PAU结构
            ElseIf PlantGroupType = "Area" Then

                If DS.GetPlantGroup(objplantGroup.ParentID).Attributes("PlantGroupType").Value = "Area" Then
                    sPlantGroupID = objplantGroup.ParentID
                End If
            End If

        Else
            sPlantGroupID = ""
        End If
        Return sPlantGroupID
        objplantGroup = Nothing
        DS = Nothing
    End Function

    Public Function GetobjitemID(DS As LMADataSource， itemtype As String, DrawingName As String) As ArrayList


        Dim oPlantItem As LMPlantItem
        Dim oPlantItems As LMPlantItems
        Dim oItems As New LMAItems
        Dim oItem As LMAItem
        Dim ItemID As New ArrayList
        Dim objFilter As LMAFilter


        Dim codeslistindex As Integer
        objFilter = New LMAFilter

        codeslistindex = DS.CodeList("Plant Item Type").EnumeratedAttributes.GetItemIndex(itemtype)

        objFilter.ItemType = "PlantItem"
        objFilter.Criteria.AddNew("2")
        objFilter.Criteria.Item("2").SourceAttributeName = "PlantItemType"
        'objFilter.Criteria.Item("2").ValueAttribute = Ds.CodeList("Plant Item Type").EnumeratedAttributes.GetItemIndex(itemtype)
        objFilter.Criteria.Item("2").ValueAttribute = codeslistindex

        objFilter.Criteria.Item("2").Operator = "="

        objFilter.Criteria.AddNew("1")
        objFilter.Criteria.Item("1").SourceAttributeName = "Representation.InStockpile"
        objFilter.Criteria.Item("1").ValueAttribute = 1
        objFilter.Criteria.Item("1").Operator = "="
        objFilter.Criteria.Item("1").Conjunctive = True

        objFilter.Criteria.AddNew("3")
        objFilter.Criteria.Item("3").SourceAttributeName = "Representation.Drawing.Name"
        objFilter.Criteria.Item("3").ValueAttribute = DrawingName
        objFilter.Criteria.Item("3").Operator = "="
        objFilter.Criteria.Item("3").Conjunctive = True

        oPlantItems = New LMPlantItems

        oPlantItems.Collect(DS, Filter:=objFilter)

        For Each oPlantItem In oPlantItems
            Dim sItemTag As String
            If IsDBNull(oPlantItem.Attributes("ItemTag").Value) = False Then
                sItemTag = oPlantItem.Attributes("ItemTag").Value
            Else
                sItemTag = "ItemTag isNull"
            End If

            ItemID.Add(oPlantItem.Attributes("SP_ID").Value & "#" & DrawingName & " " & itemtype & " " & sItemTag)    '为了写日志的时候方便获取图纸名称， itemtag属性

        Next
        Return ItemID

        oPlantItem = Nothing
        oPlantItems = Nothing
        oItems = Nothing
        oItem = Nothing
        ItemID = Nothing
        objFilter = Nothing
    End Function
    Private Sub RadGvidViewDralist_ContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGvidViewDralist.ContextMenuOpening


        'Dim separator1 As RadMenuSeparatorItem = New RadMenuSeparatorItem()  ‘可以添加菜单选项之间的分割线
        'Dim separator2 As RadMenuSeparatorItem = New RadMenuSeparatorItem()


        For i As Integer = 0 To e.ContextMenu.Items.Count - 1               '隐藏部分不常用的菜单选项
            Dim contextMenuText As String = e.ContextMenu.Items(i).Text
            Dim CeLLContextMenname As String = e.ContextMenu.Name
            Select Case contextMenuText
                Case "Conditional Formatting"
                    e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
                    e.ContextMenu.Items(i + 1).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
                Case "Hide Column"
                    e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
                Case "Pinned state"
                    e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
                Case "Column Chooser"
                    e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
                Case "Group by this column"
                    e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed
            End Select
        Next

        Dim customMenuItem1 As RadMenuItem = New RadMenuItem()   '原来在Form Load定义变量，几次操作之后会报错，所以改到这里每次都重新实例化
        Dim customMenuItem2 As RadMenuItem = New RadMenuItem()
        AddHandler customMenuItem1.Click, AddressOf Me.CustomMenuItem1_Click
        AddHandler customMenuItem2.Click, AddressOf Me.CustomMenuItem2_Click

        'Dim customMenuItem1 As RadMenuItem = New RadMenuItem()
        'Dim customMenuItem2 As RadMenuItem = New RadMenuItem()

        customMenuItem1.Text = "Paste Column"
        customMenuItem2.Text = "Clear Column"
        Dim cell As GridDataCellElement = TryCast(e.ContextMenuProvider, GridDataCellElement)
        If cell Is Nothing Then
            Return
        End If
        'set the first context menu to be displayed for cells in the second column
        If cell.ColumnIndex > -1 Or cell.RowIndex > -1 Then   '如果鼠标所在的位置不是表头或者最左侧的时候，增加右键菜单选项
            e.ContextMenu.Items.Add(customMenuItem1)
            e.ContextMenu.Items.Add(customMenuItem2)
        End If


    End Sub
    Private Sub CustomMenuItem1_Click(ByVal sender As Object, ByVal e As EventArgs)  '为新增加的右键菜单添加Click事件
        Dim i As Integer
        Dim text As String
        Dim ColumnIndex As Integer
        text = Clipboard.GetText.ToString  '获取黏贴板上的内容

        Dim cell As GridDataCellElement = RadGvidViewDralist.CurrentCell  '获取当前的单元格
        ColumnIndex = cell.ColumnIndex   '获取当前单元格的列

        For i = 0 To RadGvidViewDralist.Rows.Count - 1

            RadGvidViewDralist.Rows(i).Cells(ColumnIndex).Value = text

        Next

    End Sub
    '   Sample

    Private Sub CustomMenuItem2_Click(ByVal sender As Object, ByVal e As EventArgs)  '为新增加的右键菜单添加Click事件

        Dim i As Integer
        Dim ColumnIndex As Integer

        Dim cell As GridDataCellElement = RadGvidViewDralist.CurrentCell  '获取当前的单元格
        ColumnIndex = cell.ColumnIndex   '获取当前单元格的列

        For i = 0 To RadGvidViewDralist.Rows.Count - 1
            RadGvidViewDralist.Rows(i).Cells(ColumnIndex).Value = ""
        Next
    End Sub


    Private Sub RadBtnSeleLabel_Click(sender As Object, e As EventArgs) Handles RadBtnSeleLabel.Click
        Dim i As Integer, j As Integer
        Dim sFileWholePath As String
        Dim sFile() As String

        With RadOpenFileDialog1

            .InitialDirectory = strSymbolpath
            RadOpenFileDialog1.RestoreDirectory = True
            .Filter = "*.sym|*.sym"

        End With
        If RadOpenFileDialog1.ShowDialog() = DialogResult.OK Then

            sFileWholePath = RadOpenFileDialog1.FileName
        Else
            Exit Sub
        End If

        If sFileWholePath <> "" Then
            sFile = Split(sFileWholePath, "\")
            sSymbolName = sFile(UBound(sFile))

            i = Len(sFileWholePath)
            j = Len(strSymbolpath)
            sFilePath = Strings.Right(sFileWholePath, i - j)
        End If


        RadTextBoxLabelPath.Text = sFilePath  '   \Equipment\Labels - Equipment\Equipment ID.sym

    End Sub
    Private Sub RadBtnDeleteLabel_Click(sender As Object, e As EventArgs) Handles RadBtnDeleteLabel.Click
        SelectedDrawing()  '查询出所有勾选的图纸
        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to delete selected labels?", "Delete Labels", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
            If sSymbolName = "" Then
                RadMessageBox.Show("Please Select Label")
                Exit Sub
            ElseIf m_DrawingList.Count = 0 Then
                RadMessageBox.Show("Please Select drawings !")
                Exit Sub
            End If

            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim labelPersists As LMLabelPersists
            Dim labelPersist As LMLabelPersist
            Dim labPers As LMLabelPersist
            Dim objPIDADrawing As InteropPidAuto.Drawing
            Dim i As Integer
            Dim sDrawigName As String

            iIndex = 0
            DS = New LMADataSource
            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = False

            Catch
                MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                objPIDAutoApp = Nothing
                objPIDADrawing = Nothing
                Exit Sub
            End Try

            iTotal = m_DrawingList.Count

            ProBarDeleteLabel.Value = 0
            ProBarDeleteLabel.Maximum = m_DrawingList.Count
            ProBarDeleteLabel.Minimum = 0
            For i = 0 To m_DrawingList.Count - 1
                sDrawigName = m_DrawingList.Item(i)
                Dim filter As LMAFilter
                filter = New LMAFilter
                With filter.Criteria
                    .AddNew("1")
                    .Item("1").SourceAttributeName = "Drawing.Name"
                    .Item("1").Operator = "="
                    .Item("1").ValueAttribute = sDrawigName
                    .Item("1").Conjunctive = True
                    .AddNew("2")
                    .Item("2").SourceAttributeName = "FileName"
                    .Item("2").Operator = "="
                    .Item("2").ValueAttribute = sFilePath
                    .Item("2").Conjunctive = True
                    .AddNew("3")
                    .Item("3").SourceAttributeName = "InStockpile"
                    .Item("3").Operator = "="
                    .Item("3").ValueAttribute = 1
                    .Item("3").Conjunctive = True
                    .AddNew("4")
                    .Item("4").SourceAttributeName = "ItemStatus"
                    .Item("4").Operator = "="
                    .Item("4").ValueAttribute = 1
                    .Item("4").Conjunctive = True
                    .AddNew("5")
                    .Item("5").SourceAttributeName = "RepresentationClass"
                    .Item("5").Operator = "="
                    .Item("5").ValueAttribute = 12   'Label
                    .Item("5").Conjunctive = True
                End With

                filter.ItemType = "LabelPersist"
                labelPersists = New LMLabelPersists
                labelPersists.Collect(DS, Filter:=filter)
                If labelPersists.Count <> 0 Then
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList.Item(i))
                        If Not objPIDADrawing Is Nothing Then
                            Try
                                Dim blnDeleted As Boolean
                                Dim place As Placement
                                place = New Placement
                                For Each labelPersist In labelPersists
                                    labPers = place.PIDDataSource.GetLabelPersist(labelPersist.Id)
                                    blnDeleted = place.PIDRemovePlacement(labPers.AsLMRepresentation) ' works OK !!!
                                Next
                                LogList.Add(“Delete Label“ & CONNMARK & m_DrawingList.Item(i) & "         Delete All the Label Successfully")
                            Catch ex As Exception
                                LogList.Add(“Delete Label“ & CONNMARK & m_DrawingList.Item(i) & "    Error Delete Label Failed" & ex.Message)
                            End Try
                            objPIDADrawing.CloseDrawing(True)
                        Else
                            LogList.Add(“Delete Label“ & CONNMARK & m_DrawingList.Item(i) & "    Error Opening Drawing Failed")
                        End If
                    Catch ex As Exception
                        LogList.Add(“Delete Label“ & CONNMARK & m_DrawingList.Item(i) & "    Can't Open this Drawing " & ex.Message)
                    End Try
                End If
                ProBarDeleteLabel.Value = i + 1
            Next

            objPIDADrawing = Nothing
            labPers = Nothing
            labelPersists = Nothing
            labelPersist = Nothing
            m_DrawingList.Clear()
            Try
                objPIDAutoApp.Quit()
            Catch ex As Exception
                LogList.Add(“Delete Label“ & CONNMARK & "    Can't Quit PID " & ex.Message)
            End Try

        Else
            Exit Sub
        End If
        Call ExcuteLog(LogList)
        RadMessageBox.Show("Finish Delete Label !")
    End Sub

    Private Sub RadBtnSelectItemNote_Click(sender As Object, e As EventArgs) Handles RadBtnSelectItemNote.Click
        Dim i As Integer, j As Integer
        Dim sFileWholePath As String
        Dim sFile() As String

        With RadOpenFileDialog2

            .InitialDirectory = strSymbolpath
            RadOpenFileDialog2.RestoreDirectory = True
            .Filter = "*.sym|*.sym"

        End With
        If RadOpenFileDialog2.ShowDialog() = DialogResult.OK Then

            sFileWholePath = RadOpenFileDialog2.FileName
        Else
            Exit Sub
        End If

        If sFileWholePath <> "" Then
            sFile = Split(sFileWholePath, "\")
            sSymbolName = sFile(UBound(sFile))

            i = Len(sFileWholePath)
            j = Len(strSymbolpath)
            sFilePath = Strings.Right(sFileWholePath, i - j)
        End If


        RadTextItemNotePath.Text = sFilePath  '   \Equipment\Labels - Equipment\Equipment ID.sym
    End Sub

    Private Sub RadButton5_Click(sender As Object, e As EventArgs) Handles RadButton5.Click


        RadCheckedListBox1.AllowRemove = True

        Dim sNote As String

        sNote = RadTextBox3.Text

        RadCheckedListBox1.Items.Add(sNote)
    End Sub

    Private Sub RadButton7_Click(sender As Object, e As EventArgs) Handles RadButton7.Click

        SelectedDrawing()  '查询出所有勾选的图纸
        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to Place selected Note?", "Place Notes", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
            If sSymbolName = "" Then
                RadMessageBox.Show("Please Select Note")
                Exit Sub
            ElseIf m_DrawingList.Count = 0 Then
                RadMessageBox.Show("Please Select drawings !")
                Exit Sub
            End If


            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objNoteHeadSymbol As LMSymbol
            Dim objNote As LMItemNote
            Dim objPIDADrawing As InteropPidAuto.Drawing
            Dim i As Integer
            Dim sDrawigName As String
            Dim Index As Integer


            iIndex = 0
            sMsg = "Placing"

            DS = New LMADataSource

            DS.BeginTransaction()


            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = False

            Catch
                MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")

                objPIDAutoApp = Nothing
                objPIDADrawing = Nothing
                Exit Sub
            End Try

            iTotal = m_DrawingList.Count
            For i = 0 To m_DrawingList.Count - 1
                sDrawigName = m_DrawingList.Item(i)
                objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList.Item(i))
                Try
                    Dim place As Placement
                    place = New Placement
                    If CheckBox1.Checked Then  '需要防止备注两个字
                        objNoteHeadSymbol = place.PIDPlaceSymbol(sFilePath, 0.6858, 0.5766) '图框长-内边框距-备注线距+6.35mm
                        DS = New LMADataSource
                        objNote = DS.GetItemNote(objNoteHeadSymbol.ModelItemID)
                        objNote.Attributes("Note.Body").Value = "备注："
                        objNote.Commit()
                        For Index = 0 To RadCheckedListBox1.Items.Count
                            If RadCheckedListBox1.Items(Index).CheckState Then
                                objNoteHeadSymbol = place.PIDPlaceSymbol(sFilePath, 0.6939, 0.571 - 0.00635 * Index) '图框长-内边框距-备注线距+6.35mm
                                DS = New LMADataSource   '放置新的Note需要初始化才能获取到
                                objNote = DS.GetItemNote(objNoteHeadSymbol.ModelItemID)
                                objNote.Attributes("Note.Body").Value = RadCheckedListBox1.Items(Index).Text
                                objNote.Commit()

                            End If
                        Next

                    Else   '不需要放置 备注两个字

                        For Index = 0 To RadCheckedListBox1.Items.Count - 1
                            If RadCheckedListBox1.Items(Index).CheckState Then
                                objNoteHeadSymbol = place.PIDPlaceSymbol(sFilePath, 0.841 - 0.01 - 0.13 + 0.00635, 0.594 - 0.01 - 0.0254 - 0.0095 - 0.00635 * Index) '图框长-内边框距-备注线距+6.35mm
                                DS = New LMADataSource   '放置新的Note需要初始化才能获取到
                                objNote = DS.GetItemNote(objNoteHeadSymbol.ModelItemID)
                                objNote.Attributes("Note.Body").Value = RadCheckedListBox1.Items(Index).Text
                                objNote.Commit()

                            End If
                        Next

                    End If

                Catch ex As Exception

                End Try

                'k = k + 1
                objPIDADrawing.CloseDrawing(True)

                'RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, iIndex, iTotal, sMsg)
                'ProgressBar1.Value = k
                'ProgressBar1.Visible = True


                'iIndex = iIndex + 1
            Next
            DS.CommitTransaction()

            objPIDADrawing = Nothing
            objNoteHeadSymbol = Nothing

            m_DrawingList.Clear()
        Else
            Exit Sub
        End If
        RadMessageBox.Show("Finish Placed !")
    End Sub

    Private Sub RadButton8_Click(sender As Object, e As EventArgs) Handles RadButton8.Click

        Dim i As Integer, j As Integer
        Dim sFileWholePath As String
        Dim sFile() As String

        With RadOpenFileDialog2

            .InitialDirectory = strSymbolpath
            RadOpenFileDialog2.RestoreDirectory = True
            .Filter = "*.sym|*.sym"

        End With
        If RadOpenFileDialog2.ShowDialog() = DialogResult.OK Then

            sFileWholePath = RadOpenFileDialog2.FileName
        Else
            Exit Sub
        End If

        If sFileWholePath <> "" Then
            sFile = Split(sFileWholePath, "\")
            sSymbolName = sFile(UBound(sFile))

            i = Len(sFileWholePath)
            j = Len(strSymbolpath)
            sFilePath = Strings.Right(sFileWholePath, i - j)
        End If
        RadTextBox4.Text = sFilePath  '   \Equipment\Labels - Equipment\Equipment ID.sym
    End Sub


    Private Sub BtnDelRevisionCloud_Click(sender As Object, e As EventArgs) Handles BtnDelRevisionCloud.Click
        SelectedDrawing()  '查询出所有勾选的图纸
        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to delete selected Revision Cloud?", "Delete Revision Cloud", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
            If sSymbolName = "" Then
                RadMessageBox.Show("Please Select Revision Cloud!")
                Exit Sub
            ElseIf m_DrawingList.Count = 0 Then
                RadMessageBox.Show("Please Select drawings!")
                Exit Sub
            End If

            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objAreaBreak As LMAreaBreak
            Dim objAreaBreaks As LMAreaBreaks
            Dim objAreaBreaksRevs As LMAreaBreaks
            Dim objItem As LMAItem
            Dim objPlacement As Placement
            Dim IndexRevisionCount As Integer
            Dim objPIDADrawing As InteropPidAuto.Drawing
            Dim i As Integer
            Dim sDrawigName As String

            IndexRevisionCount = 0
            iIndex = 0


            DS = New LMADataSource
            objPlacement = New Placement
            ProBarDeleRevisionCloud.Value = 0   '初始化
            ProBarDeleRevisionCloud.Maximum = m_DrawingList.Count
            ProBarDeleRevisionCloud.Minimum = 0
            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = False
            Catch
                MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")

                objPIDAutoApp = Nothing
                objPIDADrawing = Nothing
                Exit Sub
            End Try

            iTotal = m_DrawingList.Count
            For i = 0 To m_DrawingList.Count - 1

                sDrawigName = m_DrawingList.Item(i)

                Dim iRevNumber As String
                iRevNumber = ""
                iRevNumber = Strings.Trim(RadTextRevisionNumber.Text)
                Dim filter As LMAFilter
                filter = New LMAFilter
                With filter.Criteria
                    .AddNew("1")
                    .Item("1").SourceAttributeName = "Drawing.Name"
                    .Item("1").Operator = "="
                    .Item("1").ValueAttribute = sDrawigName
                    .Item("1").Conjunctive = True
                    .AddNew("2")
                    .Item("2").SourceAttributeName = "Representation.FileName"
                    .Item("2").Operator = "="
                    .Item("2").ValueAttribute = sFilePath
                    .Item("2").Conjunctive = True
                    '.AddNew("3")    '使用此过滤条件会报错，不合法的标准，所以就在后边判断RevisionNumber属性了
                    '.Item("3").SourceAttributeName = "Revision.RevisionNumber"
                    '.Item("3").Operator = "="
                    '.Item("3").ValueAttribute = iRevNumber
                    '.Item("3").Conjunctive = True
                    ''.AddNew("4")
                    '.Item("4").SourceAttributeName = "Package.PlantItemGroupType"   ’这个过滤条件也会报错，所以就使用下边的条件来筛选过Revision Cloud
                    '.Item("4").Operator = "="
                    '.Item("4").ValueAttribute = 65   ' Revision Cloud
                    '.Item("4").Conjunctive = True
                    .AddNew("3")
                    .Item("3").SourceAttributeName = "AreaBreakType"
                    .Item("3").Operator = "="
                    .Item("3").ValueAttribute = "2"   'Curve
                    .Item("3").Conjunctive = True

                End With

                filter.ItemType = "AreaBreak"
                objAreaBreaks = New LMAreaBreaks
                objAreaBreaks.Collect(DS, Filter:=filter）
                objAreaBreaksRevs = New LMAreaBreaks
                If objAreaBreaks.Count <> 0 Then
                    If Not iRevNumber = "" Then  '如果没有给RevisionNumber，删除所有的Revision Cloud
                        For Each objAreaBreak In objAreaBreaks
                            If Not objAreaBreak.Attributes("Revision.RevisionNumber") Is Nothing Then '排除没有放置Revision Triangle的云线，如果不放置，没有RevisionNumber属性
                                If Not IsDBNull(objAreaBreak.Attributes("Revision.RevisionNumber").Value) Then  '排除没有填写RevisionNumber属性的云线
                                    If objAreaBreak.Attributes("Revision.RevisionNumber").Value = iRevNumber Then
                                        objAreaBreaksRevs.Add(objAreaBreak)
                                        'IndexRevisionCount = IndexRevisionCount + 1
                                    End If
                                End If
                            End If
                        Next
                        If objAreaBreaksRevs.Count > 0 Then
                            Try
                                objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList.Item(i)) '如果有满足条件的云线，开图删掉云线，否则不开图
                                If Not objPIDADrawing Is Nothing Then
                                    Try
                                        Dim blnDeleted As Boolean
                                        Dim place As Placement
                                        place = New Placement
                                        For Each objAreaBreak In objAreaBreaksRevs
                                            objItem = place.PIDDataSource.GetAreaBreak(objAreaBreak.Id).AsLMAItem
                                            blnDeleted = False
                                            blnDeleted = objPlacement.PIDDeleteItem(objItem) ' works OK !!!
                                        Next
                                        LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "     RevisionNumber=" & iRevNumber & "     Delete Revision Cloud Successfully")

                                    Catch ex As Exception
                                        LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Error Delete Revision Cloud Failed" & ex.Message)
                                    End Try
                                    objPIDADrawing.CloseDrawing(True)
                                Else
                                    LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Error Opening Drawing Failed")

                                End If
                            Catch ex As Exception
                                LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Can't Open this Drawing " & ex.Message)
                            End Try
                        Else
                            LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    RevisionNumber=" & iRevNumber & "     Not Found in this Drawing")
                        End If
                    Else
                        '如果没有填写工具界面Revision Number，则忽略RevisionNumber的判定条件
                        Try
                            objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList.Item(i))
                            If Not objPIDADrawing Is Nothing Then
                                Try
                                    Dim blnDeleted As Boolean
                                    Dim place As Placement
                                    place = New Placement
                                    For Each objAreaBreak In objAreaBreaks
                                        objItem = place.PIDDataSource.GetAreaBreak(objAreaBreak.Id).AsLMAItem
                                        blnDeleted = False
                                        blnDeleted = objPlacement.PIDDeleteItem(objItem) ' works OK !!!
                                    Next
                                    LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "         Delete All the Revision Cloud Successfully")
                                Catch ex As Exception
                                    LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Error Delete Revision Cloud Failed" & ex.Message)
                                End Try

                                objPIDADrawing.CloseDrawing(True)
                            Else
                                LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Error Opening Drawing Failed")
                            End If
                        Catch ex As Exception
                            LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    Can't Open this Drawing " & ex.Message)
                        End Try
                    End If
                Else
                    LogList.Add(“Delete Revision Cloud“ & CONNMARK & m_DrawingList.Item(i) & "    No Revision Cloud Found in this Drawing")
                End If
                ProBarDeleRevisionCloud.Value = i + 1
            Next

            objPIDADrawing = Nothing
            objAreaBreak = Nothing
            objAreaBreaks = Nothing
            objAreaBreaksRevs = Nothing
            objItem = Nothing
            m_DrawingList.Clear()
            Try
                objPIDAutoApp.Quit()
            Catch ex As Exception
                LogList.Add(“Delete Revision Cloud“ & CONNMARK & "Can't Quit PID Application ")
            End Try

        Else
            LogList.Add(“Delete Revision Cloud“ & CONNMARK & "Terminate delete Revision Cloud ")
            Exit Sub
        End If
        Call ExcuteLog(LogList)
        RadMessageBox.Show("Finish Delete !")
    End Sub
    'Private Sub RbtnDisplaySet_Click(sender As Object, e As EventArgs) Handles RbtnDisplaySet.Click

    '    Dim pidAutoApp As InteropPidAuto.Application
    '    pidAutoApp = New InteropPidAuto.Application
    '    Dim displaySets As InteropIDisplaySetinf.ISPDisplaySets
    '    displaySets = pidAutoApp.ActiveDrawing.ViewDisplaySets
    '    Dim dispSet As InteropIDisplaySetinf.ISPDisplaySet
    '    dispSet = displaySets.Item(3) ' Flow Direction
    '    pidAutoApp.ActiveDrawing.ApplyDisplaySet(dispSet)
    '    'Debug.Print "Display Set '" & dispSet.Name & "' is active."
    '    pidAutoApp.ClearAll
    '    displaySets = Nothing
    '    dispSet = Nothing
    '    pidAutoApp = Nothing
    'End Sub
    Public Sub New()
        InitializeComponent()
        provider = New MyShortcutProvider()
        provider.Shortcuts.Add(New RadShortcut(Keys.Control, Keys.F))
    End Sub

    Private Sub btnDeleteAll_Click(sender As Object, e As EventArgs) Handles btnDeleteAll.Click

        SelectedDrawing()  '查询出所有勾选的图纸
        If CheckRevision.Checked = False And CheckVersion.Checked = False Then
            RadMessageBox.Show("Please select Revison or Version need to be deleted")
            Exit Sub
        ElseIf m_DrawingList.Count = 0 Then
            RadMessageBox.Show("Please Select Drawings!")
            Exit Sub
        ElseIf m_DrawingList.Count > 0 Then
            DwgIDs = ""
            For i = 0 To m_DrawingIDList.Count - 1
                DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
            Next
            DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
            ReadUserAndPs_in_PID()   '获取DBtypePID
            ReadAllDBUserAndPs()

            If CheckRevision.Checked = True And CheckVersion.Checked = True Then
                DeleteAllRevisionandVersion(DwgIDs, "Revision and Version")
            ElseIf CheckRevision.Checked = True And CheckVersion.Checked = False Then
                DeleteAllRevisionandVersion(DwgIDs, "Revision")
            ElseIf CheckRevision.Checked = False And CheckVersion.Checked = True Then
                DeleteAllRevisionandVersion(DwgIDs, "Version")
            End If

        End If

    End Sub
    Private Sub btnDeletebyProp_Click(sender As Object, e As EventArgs) Handles btnDeletebyProp.Click

        SelectedDrawing()  '查询出所有勾选的图纸

        If TXTMajorRevision.Text = "" And TXTMinorRevision.Text = "" Then
            RadMessageBox.Show("Please fill in MajorRevision or Minor Revision ")
            Exit Sub
        ElseIf m_DrawingList.Count = 0 Then
            RadMessageBox.Show("Please Select Drawings!")
            Exit Sub
        ElseIf m_DrawingList.Count > 0 Then
            DwgIDs = ""
            For i = 0 To m_DrawingIDList.Count - 1
                DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
            Next
            DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
            ReadUserAndPs_in_PID()   '获取DBtypePID
            ReadAllDBUserAndPs()

            If Not TXTMajorRevision.Text = "" And Not TXTMinorRevision.Text = "" Then
                DeleteRevisionandVersionbyProp(DwgIDs, "Major and Minor Revision")
            ElseIf Not TXTMajorRevision.Text = "" And TXTMinorRevision.Text = "" Then
                DeleteRevisionandVersionbyProp(DwgIDs, "Major Revision")
            End If

        End If
    End Sub


    Private Sub btnDeletebyTime_Click(sender As Object, e As EventArgs) Handles btnDeletebyTime.Click
        SelectedDrawing()  '查询出所有勾选的图纸
        If m_DrawingList.Count = 0 Then
            RadMessageBox.Show("Please Select Drawings!")
            Exit Sub
        ElseIf m_DrawingList.Count > 0 Then
            DwgIDs = ""
            For i = 0 To m_DrawingIDList.Count - 1
                DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
            Next
            DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
            ReadUserAndPs_in_PID()   '获取DBtypePID
            ReadAllDBUserAndPs()

            If CheckRevisionandVersion.CheckedItems.Count = 2 Then
                DeleteRevisionandVersionbyTime(DwgIDs, "Revision and Version")
            ElseIf CheckRevisionandVersion.CheckedItems(0).Text = "Revision" Then
                DeleteRevisionandVersionbyTime(DwgIDs, "Revision")
            ElseIf CheckRevisionandVersion.CheckedItems(0).Text = "Version" Then
                DeleteRevisionandVersionbyTime(DwgIDs, "Version")
            End If

        End If
    End Sub
    '    Dim dr As DialogResult = RadMessageBox.Show("Are you sure to Place selected Note?", "Place Notes", MessageBoxButtons.YesNo, RadMessageIcon.Question)
    'If dr = DialogResult.Yes Then
    '    If sSymbolName = "" Then
    '        RadMessageBox.Show("Please Select Note")
    '        Exit Sub
    '    ElseIf m_DrawingList.Count = 0 Then
    '        RadMessageBox.Show("Please Select drawings !")
    '        Exit Sub
    '    End If

    Public Sub DeleteAllRevisionandVersion(sID As String, sDeleteobject As String)

        If sDeleteobject = "Revision and Version" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Revision and Version", "All", "ORACLE")
        ElseIf sDeleteobject = "Revision and Version" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Revision and Version", "All", "SQLSERVER")
        ElseIf sDeleteobject = "Revision" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Revision", "All", "ORACLE")
        ElseIf sDeleteobject = "Revision" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Revision", "All", "SQLSERVER")
        ElseIf sDeleteobject = "Version" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Version", "All", "ORACLE")
        ElseIf sDeleteobject = "Version" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Version", "All", "SQLSERVER")
        End If

    End Sub

    Public Sub DeleteRevisionandVersionbyTime(sID As String, sDeleteobject As String)
        If sDeleteobject = "Revision and Version" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Revision and Version", "Time", "ORACLE")
        ElseIf sDeleteobject = "Revision and Version" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Revision and Version", "Time", "SQLSERVER")
        ElseIf sDeleteobject = "Revision" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Revision", "Time", "ORACLE")
        ElseIf sDeleteobject = "Revision" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Revision", "Time", "SQLSERVER")
        ElseIf sDeleteobject = "Version" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Version", "Time", "ORACLE")
        ElseIf sDeleteobject = "Version" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Version", "Time", "SQLSERVER")
        End If
    End Sub

    Public Sub DeleteRevisionandVersionbyProp(sID As String, sDeleteobject As String)
        If sDeleteobject = "Major and Minor Revision" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Major and Minor Revision", "Prop", "ORACLE")
        ElseIf sDeleteobject = "Major and Minor Revision" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Major and Minor Revision", "Prop", "SQLSERVER")
        ElseIf sDeleteobject = "Major Revision" And DBTypePID = "ORACLE" Then
            RunScript(sID, "Major Revision", "Prop", "ORACLE")
        ElseIf sDeleteobject = "Major Revision" And DBTypePID = "SQLSERVER" Then
            RunScript(sID, "Major Revision", "Prop", "SQLSERVER")
        End If
    End Sub


    Public Sub RunScript(sID As String, sData As String, sMethod As String, sDataBaseType As String)
        Dim DS As New LMADataSource
        Dim XEndDate As String
        Dim XStartDate As String

        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to delete Revision or Version ?", "Delete Revision and Version", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then

            If sMethod = "All" Then
                If sDataBaseType = "ORACLE" Then

                    sDeleteRevision = ""
                    sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision t
    where t.sp_drawingID in (xDWGIDS) 
                        </string>.Value
                    sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                    'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)

                    sDeleteVersion = ""
                    sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  t
    where t.sp_drawingID in (xDWGIDS)
                        </string>.Value
                    sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                    'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)


                    If sData = "Version" Then
                        sDeleteRevision = ""
                    ElseIf sData = "Revision" Then
                        sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS) and SP_REVISIONID is not null
                        </string>.Value

                        sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                        'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                    End If
                ElseIf sDataBaseType = "SQLSERVER" Then
                    sDeleteRevision = ""
                    sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision 
    where sp_drawingID in (xDWGIDS) 
                        </string>.Value
                    sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                    'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)

                    sDeleteVersion = ""
                    sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS)
                        </string>.Value
                    sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                    'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)


                    If sData = "Version" Then
                        sDeleteRevision = ""
                    ElseIf sData = "Revision" Then
                        sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS) and SP_REVISIONID is not null
                        </string>.Value

                        sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                        'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                    End If

                End If

            ElseIf sMethod = "Time" Then

                'XStartDate = StartDate.Value
                ''XEndDate = Format(DateAdd("d", 1, EndDate.Value), "mm-dd-yyyy")  '加一天时间，所取数值包含Start Date 和End Date


                'XEndDate = DateAdd("d", 1, EndDate.Value)
                XStartDate = StartDate.Value.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)

                XEndDate = DateAdd("d", 1, EndDate.Value).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
                If sDataBaseType = "ORACLE" Then
                    sDeleteRevision = ""
                    sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision t
     where t.sp_revisiondate BETWEEN TO_DATE ('XStartDate', 'yyyy/MM/dd') AND TO_DATE ('XEndDate', 'yyyy/MM/dd') and t.sp_drawingid in (xDWGIDS)
                        </string>.Value
                    sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                    sDeleteRevision = Replace(sDeleteRevision, "XStartDate", XStartDate)
                    sDeleteRevision = Replace(sDeleteRevision, "XEndDate", XEndDate)

                    'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)
                    sDeleteVersion = ""
                    sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  t
     where t.DATECREATED BETWEEN TO_DATE ('XStartDate', 'yyyy/MM/dd') AND TO_DATE ('XEndDate', 'yyyy/MM/dd') and t.sp_drawingid in (xDWGIDS)
                        </string>.Value

                    sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                    sDeleteVersion = Replace(sDeleteVersion, "XStartDate", XStartDate)
                    sDeleteVersion = Replace(sDeleteVersion, "XEndDate", XEndDate)
                    'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)

                    If sData = "Version" Then
                        sDeleteRevision = ""
                    ElseIf sData = "Revision" Then
                        sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  t
    where t.sp_drawingID in (xDWGIDS) and t.SP_REVISIONID is not null and t.DATECREATED BETWEEN TO_DATE ('XStartDate', 'yyyy/MM/dd') AND TO_DATE ('XEndDate', 'yyyy/MM/dd')
                        </string>.Value

                        sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                        sDeleteVersion = Replace(sDeleteVersion, "XStartDate", XStartDate)
                        sDeleteVersion = Replace(sDeleteVersion, "XEndDate", XEndDate)
                        'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                    End If
                ElseIf sDataBaseType = "SQLSERVER" Then
                    Dim sStartDate As String
                    Dim sEndDate As String

                    sStartDate = XStartDate  '转化日期的格式，由'mm/dd/yyyy'转化为20210718 （yyyymmdd）
                    sEndDate = XEndDate
                    sDeleteRevision = ""
                    sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision 
     where SP_RevisionDate BETWEEN  'XStartDate' and 'XEndDate' and sp_drawingid in (xDWGIDS)
                        </string>.Value
                    sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                    sDeleteRevision = Replace(sDeleteRevision, "XStartDate", sStartDate)
                    sDeleteRevision = Replace(sDeleteRevision, "XEndDate", sEndDate)

                    'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)
                    sDeleteVersion = ""
                    sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
     where DATECREATED BETWEEN 'XStartDate' and 'XEndDate' and sp_drawingid in (xDWGIDS)
                        </string>.Value

                    sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                    sDeleteVersion = Replace(sDeleteVersion, "XStartDate", sStartDate)
                    sDeleteVersion = Replace(sDeleteVersion, "XEndDate", sEndDate)
                    'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)

                    If sData = "Version" Then
                        sDeleteRevision = ""
                    ElseIf sData = "Revision" Then
                        sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS) and SP_REVISIONID is not null and where DATECREATED BETWEEN 'XStartDate' and 'XEndDate' 
                        </string>.Value

                        sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                        sDeleteVersion = Replace(sDeleteVersion, "XStartDate", sStartDate)
                        sDeleteVersion = Replace(sDeleteVersion, "XEndDate", sEndDate)
                        'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                    End If
                End If

            ElseIf sMethod = "Prop" Then

                Dim sMajorRevision As String
                Dim sMinorRevision As String
                Dim sRevisionID As String
                sMajorRevision = TXTMajorRevision.Text
                sMinorRevision = TXTMinorRevision.Text

                sRevisionID = GetRevisionID(sID, sMajorRevision, sMinorRevision)
                If Not sRevisionID = "" Then
                    If sDataBaseType = "ORACLE" Then
                        If sData = "Major and Minor Revision" Then
                            'sRevisionID = GetRevisionID(sID, sMajorRevision, sMinorRevision)
                            sDeleteRevision = ""
                            sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision t
    where t.sp_drawingID in (xDWGIDS) and t.SP_MAJORREVISIONNUMBER = 'XMajorRevision' and t.SP_MINORREVISIONNUMBER = 'XMinorRevision'
                        </string>.Value
                            sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                            sDeleteRevision = Replace(sDeleteRevision, "XMajorRevision", sMajorRevision)
                            sDeleteRevision = Replace(sDeleteRevision, "XMinorRevision", sMinorRevision)
                            'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)


                            sDeleteVersion = ""
                            sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  t
    where t.sp_drawingID in (xDWGIDS) and t.SP_REVISIONID in (XRevisionID) 
                        </string>.Value
                            sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                            sDeleteVersion = Replace(sDeleteVersion, "XRevisionID", sRevisionID)
                            'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                        ElseIf sData = "Major Revision" Then

                            sDeleteRevision = ""
                            sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision t
    where t.sp_drawingID in (xDWGIDS) and t.SP_MAJORREVISIONNUMBER = 'XMajorRevision' 
                        </string>.Value
                            sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                            sDeleteRevision = Replace(sDeleteRevision, "XMajorRevision", sMajorRevision)
                            'sDeleteRevision = Replace(sDeleteRevision, "XMinorRevision", sMinorRevision)



                            sDeleteVersion = ""
                            sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  t
    where t.sp_drawingID in (xDWGIDS) and t.SP_REVISIONID in (XRevisionID) 
                        </string>.Value
                            sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                            sDeleteVersion = Replace(sDeleteVersion, "XRevisionID", sRevisionID)
                        End If
                    ElseIf sDataBaseType = "SQLSERVER" Then
                        If sData = "Major and Minor Revision" Then
                            'sRevisionID = GetRevisionID(sID, sMajorRevision, sMinorRevision)
                            sDeleteRevision = ""
                            sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision 
    where sp_drawingID in (xDWGIDS) and SP_MAJORREVISIONNUMBER = 'XMajorRevision' and SP_MINORREVISIONNUMBER = 'XMinorRevision'
                        </string>.Value
                            sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                            sDeleteRevision = Replace(sDeleteRevision, "XMajorRevision", sMajorRevision)
                            sDeleteRevision = Replace(sDeleteRevision, "XMinorRevision", sMinorRevision)
                            'sDeleteRevision = Replace(sDeleteRevision, "xxxSchemaName", ActivePlantPIDAppUser)


                            sDeleteVersion = ""
                            sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS) and SP_REVISIONID in (XRevisionID) 
                        </string>.Value
                            sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                            sDeleteVersion = Replace(sDeleteVersion, "XRevisionID", sRevisionID)
                            'sDeleteVersion = Replace(sDeleteVersion, "xxxSchemaName", ActivePlantPIDAppUser)
                        ElseIf sData = "Major Revision" Then

                            sDeleteRevision = ""
                            sDeleteRevision = <string>    
    Delete from xxxSchemaName.T_revision 
    where sp_drawingID in (xDWGIDS) and SP_MAJORREVISIONNUMBER = 'XMajorRevision' 
                        </string>.Value
                            sDeleteRevision = Replace(sDeleteRevision, "xDWGIDS", sID)
                            sDeleteRevision = Replace(sDeleteRevision, "XMajorRevision", sMajorRevision)
                            'sDeleteRevision = Replace(sDeleteRevision, "XMinorRevision", sMinorRevision)

                            sDeleteVersion = ""
                            sDeleteVersion = <string>
   Delete from xxxSchemaName.T_DrawingVersion  
    where sp_drawingID in (xDWGIDS) and SP_REVISIONID in (XRevisionID) 
                        </string>.Value
                            sDeleteVersion = Replace(sDeleteVersion, "xDWGIDS", sID)
                            sDeleteVersion = Replace(sDeleteVersion, "XRevisionID", sRevisionID)
                        End If
                    End If
                Else
                    sDeleteVersion = ""
                    sDeleteRevision = ""

                End If
            End If
        Else
            Exit Sub
        End If

        If Not sDeleteRevision = "" Then
            Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, sDeleteRevision)
        End If
        If Not sDeleteVersion = "" Then
            Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, sDeleteVersion)
        End If
        RadMessageBox.Show("Finish !")
    End Sub
    Public Function ConvertDate(Xdate As Date) As String
        Dim sDate As String
        Dim sYear, sDay, sMonth As String

        sDate = CStr(Xdate)
        sYear = Split(sDate, "/")(2)
        sMonth = Split(sDate, "/")(0)
        sDay = Split(sDate, "/")(1)

        If Len(sMonth) = 1 Then
            sMonth = 0 & sMonth
        End If
        If Len(sDay) = 1 Then
            sDay = 0 & sDay
        End If

        Return sYear + sMonth + sDay
    End Function

    Public Function GetRevisionID(sID As String, sMajorRevision As String, sMinorRevision As String) As String

        Dim i As Integer
        sSelect = ""
        Dim dtRevisionID As New DataTable
        Dim sRevisionID As String = ""

        If Not sMinorRevision = "" And Not sMajorRevision = "" Then

            sSelect = <string>
    select t.SP_ID
    from xxxSchemaName.T_revision t
     where t.sp_drawingID in (xDWGIDS) and t.SP_MAJORREVISIONNUMBER = 'XMajorRevision' and t.SP_MINORREVISIONNUMBER = 'XMinorRevision'
                        </string>.Value
            sSelect = Replace(sSelect, "xDWGIDS", sID)
            sSelect = Replace(sSelect, "XMajorRevision", sMajorRevision)
            sSelect = Replace(sSelect, "XMinorRevision", sMinorRevision)
        Else
            sSelect = <string>
    select t.SP_ID
    from xxxSchemaName.T_revision t
     where t.sp_drawingID in (xDWGIDS) and t.SP_MAJORREVISIONNUMBER = 'XMajorRevision' 
                        </string>.Value
            sSelect = Replace(sSelect, "xDWGIDS", sID)
            sSelect = Replace(sSelect, "XMajorRevision", sMajorRevision)
        End If

        PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, sSelect, dtRevisionID)

        If dtRevisionID.Rows.Count > 0 Then
            For i = 0 To dtRevisionID.Rows.Count - 1
                sRevisionID = sRevisionID + "'" + dtRevisionID(i)(0) + "',"
            Next
            sRevisionID = Mid(sRevisionID, 1, Len(sRevisionID) - 1)
        End If

        Return sRevisionID
    End Function

    Private Sub BtnMSetItemStatus_Click(sender As Object, e As EventArgs) Handles BtnMSetItemStatus.Click
        Dim sModelID() As String
        Dim sSelect As String = ""
        Dim dtModelID As New DataTable

        Dim supdate As String = ""
        Dim i As Integer

        isOK = False
        Call ReadUserAndPs_in_PID()   '获取DBtypePID
        Call ReadAllDBUserAndPs()

        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to delete object?", "Delete object", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
            If TXTModelID.Text = "" Then
                RadMessageBox.Show("Please fill in SP_ID ")
                Exit Sub

            ElseIf RadRadioModelID.IsChecked Then
                ''清理 modelitem
                If Not TXTModelID.Text = "" Then
                    sModelID = Split(TXTModelID.Text, ",")
                    isOK = False
                    sSelect = ""
                    sValidModelID = ""
                    sUValidModelID = ""
                    iValidID = 0
                    iUValidID = 0
                    For i = 0 To UBound(sModelID)
                        'If DBTypePID = "ORACLE" Then
                        sSelect = <string>
    select t.SP_ID
    from xxxSchemaName.T_MODELITEM t
     where t.SP_ID = 'XModelID'
                        </string>.Value
                        sSelect = Replace(sSelect, "XModelID", sModelID(i))


                        PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, sSelect, dtModelID)

                        If dtModelID.Rows.Count > 0 Then
                            sValidModelID = sValidModelID + "'" + sModelID(i) + "',"
                            iValidID = iValidID + 1
                        Else
                            sUValidModelID = sUValidModelID + "'" + sModelID(i) + "',"
                            iUValidID = iUValidID + 1
                        End If
                    Next


                    If iValidID > 0 Then
                        sValidModelID = Mid(sValidModelID, 1, Len(sValidModelID) - 1)
                        supdate = <string>    
     update xxxSchemaName.T_MODELITEM set itemstatus=4 
     where SP_ID IN(XValidID) 
                        </string>.Value
                        supdate = Replace(supdate, "XValidID", sValidModelID)
                    End If
                    If iUValidID > 0 Then
                        sUValidModelID = Mid(sUValidModelID, 1, Len(sUValidModelID) - 1)
                    End If

                    If Not supdate = "" Then
                        Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, supdate)
                        isOK = True
                    End If

                    frmDBCleanLog.Show()
                End If
            Else
                ''清理 representation
                If Not TXTModelID.Text = "" Then
                    sModelID = Split(TXTModelID.Text, ",")
                    sSelect = ""
                    sValidModelID = ""
                    sUValidModelID = ""
                    iValidID = 0
                    iUValidID = 0
                    isOK = False
                    For i = 0 To UBound(sModelID)
                        'If DBTypePID = "ORACLE" Then
                        sSelect = <string>
    select t.SP_ID
    from xxxSchemaName.T_REPRESENTATION t
     where t.SP_ID = 'XModelID'
                        </string>.Value
                        sSelect = Replace(sSelect, "XModelID", sModelID(i))

                        PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, sSelect, dtModelID)

                        If dtModelID.Rows.Count > 0 Then
                            sValidModelID = sValidModelID + "'" + sModelID(i) + "',"
                            iValidID = iValidID + 1
                        Else
                            sUValidModelID = sUValidModelID + "'" + sModelID(i) + "',"
                            iUValidID = iUValidID + 1
                        End If
                    Next


                    If iValidID > 0 Then
                        sValidModelID = Mid(sValidModelID, 1, Len(sValidModelID) - 1)
                        supdate = <string>    
     update xxxSchemaName.T_REPRESENTATION set itemstatus=4 
     where SP_ID IN(XValidID) 
                        </string>.Value
                        supdate = Replace(supdate, "XValidID", sValidModelID)
                    End If
                    If iUValidID > 0 Then
                        sUValidModelID = Mid(sUValidModelID, 1, Len(sUValidModelID) - 1)
                    End If

                    If Not supdate = "" Then
                        Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, supdate)
                        isOK = True
                    End If

                    frmDBCleanLog.Show()
                End If
            End If

        ElseIf dr = DialogResult.No Then
            Exit Sub
        End If
    End Sub

    Private Sub BtnCheckPath_Click(sender As Object, e As EventArgs) Handles BtnCheckPath.Click

        Dim sSelect As String = ""
        Dim dtPath As New DataTable


        Call ReadUserAndPs_in_PID()   '获取DBtypePID
        Call ReadAllDBUserAndPs()

        CheckpathList.Items.Clear()
        sSelect = <string>
    select sp_id ,filename
    from xxxSchemaName.t_representation 
     where filename like '|%'
                        </string>.Value

        PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, sSelect, dtPath)

        If dtPath.Rows.Count > 0 Then

            For i = 0 To dtPath.Rows.Count - 1

                CheckpathList.Items.Add(dtPath(i)(1))

            Next
        Else
            CheckpathList.Items.Add("No Error Path contains |")
        End If


    End Sub

    Private Sub BtnUpdatePath_Click(sender As Object, e As EventArgs) Handles BtnUpdatePath.Click
        Dim strupdate As String

        Dim i As Integer
        Dim sRightPath As String
        Dim dr As DialogResult = RadMessageBox.Show("Are you sure to update Path?", "update Path", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then

            Call ReadUserAndPs_in_PID()   '获取DBtypePID
            Call ReadAllDBUserAndPs()

            If CheckpathList.Items.Count > 0 And CheckpathList.Items(0).Value <> "No Error Path contains |" Then
                strupdate = ""
                For i = 0 To CheckpathList.Items.Count - 1
                    strupdate = <string>    
     update xxxSchemaName.T_REPRESENTATION set filename = 'XFileName'
     where filename = 'XErrorPath'
                        </string>.Value

                    sRightPath = Strings.Right(CheckpathList.Items(i).Value, Len(CheckpathList.Items(i).Value) - 1)
                    strupdate = Replace(strupdate, "XFileName", sRightPath)
                    strupdate = Replace(strupdate, "XErrorPath", CheckpathList.Items(i).Value)

                    If Not strupdate = "" Then
                        Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, strupdate)

                    End If

                Next
                RadMessageBox.Show("Finish update!")
            Else
                RadMessageBox.Show("No Path need to update!")
            End If

        Else
            Exit Sub
        End If
    End Sub

    Private Sub BtnUpdateNozzle_Click(sender As Object, e As EventArgs) Handles BtnUpdateNozzle.Click

        '初始化
        RadProgressBarElement1.Value1 = 0
        RadProgressBarElement1.Value2 = 0
        sMsg = "Update Nozzle"
        RadLabelElement1.Text = sMsg
        Call updateNozzleParentEquipment()

    End Sub

    Public Sub updateNozzleParentEquipment()

        Dim iNozzle As Integer = 0
        Dim ObjNozzle As LMNozzle
        Dim objNos As LMNozzles
        Dim objNozzles As LMNozzles
        Dim ObjEqpComp As LMEquipComponent
        Dim ObjEquipment As LMEquipment
        Dim ArrayIDs As New ArrayList
        Dim IntCount As Integer = 0
        Dim sDrawigName As String
        Dim filter As LMAFilter

        Call ReadUserAndPs_in_PID()   '获取DBtypePID
        Call ReadAllDBUserAndPs()
        SelectedDrawing()  '查询出所有勾选的图纸

        DS = New LMADataSource
        filter = New LMAFilter
        objNozzles = New LMNozzles
        objNos = New LMNozzles

        iTotal = m_DrawingList.Count
        If m_DrawingList.Count > 0 Then
            For i = 0 To m_DrawingList.Count - 1
                sDrawigName = m_DrawingList.Item(i)
                With filter.Criteria
                    .AddNew("1")
                    .Item("1").SourceAttributeName = "Representation.Drawing.Name"
                    .Item("1").Operator = "="
                    .Item("1").ValueAttribute = sDrawigName
                    .Item("1").Conjunctive = True
                End With
                filter.ItemType = "Nozzle"

                objNozzles.Collect(DS, Filter:=filter）
                ArrayIDs.Clear()
                Dim s As String
                If objNozzles.Count > 0 Then
                    For Each ObjNozzle In objNozzles
                        s = ObjNozzle.Id
                        If Not ObjNozzle.PartOfPlantItemID Is System.DBNull.Value Then
                            If ObjNozzle.PartOfPlantItemObject.Attributes("ItemTypeName").Value = "EquipComponent" Then
                                ObjEqpComp = DS.GetEquipComponent(ObjNozzle.PartOfPlantItemID)
                                If Not ObjEqpComp.PartOfPlantItemID Is System.DBNull.Value Then
                                    If ObjEqpComp.PartOfPlantItemObject.PlantItemType = "Equipment" Then
                                        ObjEquipment = DS.GetEquipment(ObjEqpComp.PartOfPlantItemID)
                                        ArrayIDs.Add(ObjNozzle.Id & "#" & ObjEquipment.Id)

                                    End If
                                End If
                            End If
                        End If
                    Next
                End If

                If ArrayIDs.Count > 0 Then
                    UpdateNozzleDataBase(ArrayIDs)
                    iNozzle = iNozzle + ArrayIDs.Count
                End If

                IntCount = IntCount + 1
                RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, IntCount, iTotal, sMsg, "")
            Next
        Else
            RadMessageBox.Show("Please select drawings")
        End If

        Dim redr As DialogResult = RadMessageBox.Show("Update Nozzles Finished！" + vbNewLine + "Total Drawings: " + iTotal.ToString + ", Total Nozzles: " + iNozzle.ToString, "Result", MessageBoxButtons.OK, RadMessageIcon.Exclamation)
        'Dim redr As DialogResult = RadMessageBox.Show("Open Drawings Finished!" + vbNewLine + "Total Drawing " + iTotal + " Of " + IntCount.ToString + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        'If redr = DialogResult.OK Then

        'End If

        DS = Nothing
        ObjNozzle = Nothing
        ObjEqpComp = Nothing
        ObjEquipment = Nothing
        objNozzles = Nothing
        ArrayIDs = Nothing

    End Sub
    Public Sub UpdateNozzleDataBase(IDs As ArrayList)
        Dim supdate As String = ""
        Dim i As Integer = 0
        Dim sNozzleID As String = ""
        Dim sEqpID As String = ""
        Dim IntCount As Integer = 0

        For i = 0 To IDs.Count - 1
            'If DBTypePID = "ORACLE" Then
            supdate = <string>    
     update xxxSchemaName.T_Nozzle set SP_EQUIPMENTID = 'XEqpID'
     where SP_ID = 'XNozzleID'
                        </string>.Value

            sNozzleID = Split(IDs(i), "#")(0)
            sEqpID = Split(IDs(i), "#")(1)
            supdate = Replace(supdate, "XEqpID", sEqpID)
            supdate = Replace(supdate, "XNozzleID", sNozzleID)

            If Not supdate = "" Then
                Call PIDUpdateDataByDBA(Plant_DBNAME, ActivePlantPIDAppUser, supdate)
            End If
        Next
        IDs = Nothing
    End Sub

    Private Sub BtnGetPath_Click(sender As Object, e As EventArgs) Handles BtnGetPath.Click

        Dim objDrawing As LMDrawing
        Dim stempName As String = ""
        Dim sTempPath As String = ""
        Dim objDoc As Ingr.RAD2D.Document
        Dim objSmartFrame2d As Ingr.RAD2D.SmartFrame2d
        Dim objSmartFrames2d As Ingr.RAD2D.SmartFrames2d
        Dim sLinkedPath As String

        DS = New LMADataSource
        Try
            Try
                initialzeSSK()
            Catch ex As Exception
                LogList.Add("Get Border Path::" & "  初始化SSK失败，请安装SSK 2016,或者手工输入模板的路径 ")
            End Try
            If Not sskApp Is Nothing Then
                SelectedDrawing()
                If m_DrawingIDList.Count > 0 Then
                    objDrawing = DS.GetDrawing(m_DrawingIDList.Item(0))
                    stempName = objDrawing.Attributes("Template").Value
                    sTempPath = GetTemplatePath(DS) & "\" & stempName
                    sTempPath = GetRefPath(DS)
                    'sTempPath = "\\ZspiD\INGR\INGR02\P&ID Reference Data\Template Files" & "\" & stempName
                    Try
                        objDoc = sskApp.Documents.Open(sTempPath, True)
                        If Not objDoc Is Nothing Then
                            objSmartFrames2d = objDoc.ActiveSheet.SmartFrames2d
                            For Each objSmartFrame2d In objSmartFrames2d
                                If (objSmartFrame2d.IsLink) Then
                                    sLinkedPath = objSmartFrame2d.LinkMoniker
                                    TextNewLinkedPath.Text = sLinkedPath
                                    LogList.Add("Get Border Path::" & "   获取模板Link Border路径成功 ")
                                    Exit For
                                End If
                            Next
                        End If
                    Catch ex As Exception
                        RadMessageBox.Show("无法获取模板Link的路径，请手工输入！")
                    End Try

                Else
                    RadMessageBox.Show("Please Select at least one Drawing")
                End If
            End If

        Catch ex As Exception
            LogList.Add("Get Border Path::" & "  ERROR Get Template Path ")
        End Try

        ReleaseCOMObjects(DS, objDrawing)
        ExcuteLog(LogList)
    End Sub
    ''' <summary>
    ''' Optiong Setting 位于Pid Schema 中表T_OptionSetting 
    ''' 
    ''' </summary>
    ''' <returns></returns>
    Private Function GetTemplatePath(datasource As LMADataSource) As String

        Dim lmacriterion As LMACriterion = New LMACriterion()
        Dim lmafilter As LMAFilter = New LMAFilter()
        lmacriterion.SourceAttributeName = "Name"
        lmacriterion.ValueAttribute = "PID Template Path"
        lmacriterion.[Operator] = "="
        lmafilter.ItemType = "OptionSetting"
        lmafilter.Criteria.Add(lmacriterion)
        Dim lmoptionSettings As LMOptionSettings = New LMOptionSettings()
        lmoptionSettings.Collect(datasource, , "", lmafilter)
        'lmoptionSettings.Collect(datasource, Nothing, "", Nothing)

        Dim lmoptionSetting As LMOptionSetting = lmoptionSettings.Nth(1)
        Return Conversions.ToString(lmoptionSetting.Value)

    End Function
    Public Function GetRefPath(ByRef datasource As LMADataSource) As String
        Dim lmacriterion As LMACriterion = New LMACriterion()
        Dim lmafilter As LMAFilter = New LMAFilter()
        lmacriterion.SourceAttributeName = "Name"
        lmacriterion.ValueAttribute = "Catalog Explorer root path"
        lmacriterion.[Operator] = "="
        lmafilter.ItemType = "OptionSetting"
        lmafilter.Criteria.Add(lmacriterion)
        Dim lmoptionSettings As LMOptionSettings = New LMOptionSettings()
        lmoptionSettings.Collect(datasource, , "", lmafilter)
        Dim lmoptionSetting As LMOptionSetting = lmoptionSettings.Nth(1)
        Return Conversions.ToString(lmoptionSetting.Value)
    End Function
    Public Sub initialzeSSK()
        ''/////////////////////////////////////////////////////////////////////////
        ''//初始化SmartSketch应用
        Dim sAppPath As String
        Dim sAppResourceName As String
        Dim sAppStartUpDllClsid As String
        Dim sAppDispatchObjectClsid As String
        Dim sAppName As String
        Dim sAppEnvironmentName As String
        sAppName = "SmartSketch"
        sAppPath = "c:\Program Files (x86)\SmartSketch\Program\"
        sAppResourceName = "SmartSketch.drx"
        sAppStartUpDllClsid = "{AF7DB05C-6427-11D5-868F-00A0C9D8948D}"
        sAppDispatchObjectClsid = "{9099087E-A96B-11D1-91A8-08003643CA02}"
        sAppEnvironmentName = "Sketch"
        sskWrapperApp = DirectCast(Ingr.RAD2D.Initialize.RADApplicationStarter.Instance.InitializeRADApplication(sAppName, sAppPath, sAppResourceName, sAppStartUpDllClsid, sAppDispatchObjectClsid, sAppEnvironmentName), Ingr.RAD2D.WrapperApplication)
        sskApp = sskWrapperApp.RADApplication
        ''/////////////////////////////////////////////////////////////////////////
    End Sub
    Private Sub BtnUpdateLinkedBorder_Click(sender As Object, e As EventArgs) Handles BtnUpdateLinkedBorder.Click

        RadProgressBarElement2.Value1 = 0
        RadProgressBarElement2.Value2 = 0
        sMsg = "Updating Border "
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 1, 100000, sMsg, "Starting")
        SelectedDrawing()  '查询出所有勾选的图纸

        RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
        Dim dr As DialogResult = RadMessageBox.Show("Do you want update border", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)

        If dr = DialogResult.Yes And m_DrawingList.Count > 0 Then
            'Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing = Nothing
            Dim i As Integer
            Dim DwgIDs As String = ""
            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0
            DS = New LMADataSource

            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = True
            Catch
                MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                Exit Sub
            End Try

            If Not objPIDAutoApp Is Nothing And CheckDeletelinked.Checked = True And CheckDeleteEmbeded.Checked = True Then
                For i = 0 To m_DrawingList.Count - 1
                    iTotal = m_DrawingList.Count
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList(i))
                        objPID2d = objPIDAutoApp.Application.radapplication

                        Try
                            ChangelinkedBorder(objPID2d, m_DrawingList(i))
                            DeletelinkedBorder(objPID2d, m_DrawingList(i))
                            DeleteEmbededBorder(objPID2d, m_DrawingList(i))
                        Catch ex As Exception

                        End Try

                        'SetXYorigin(objPID2d， m_DrawingList(i))
                    Catch ex As Exception

                        LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸未能打开")
                    End Try

                    If Not objPIDADrawing Is Nothing Then
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸关闭失败")
                        End Try
                    End If
                    RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                Next
            ElseIf CheckDeletelinked.Checked = True And CheckDeleteEmbeded.Checked = False Then
                For i = 0 To m_DrawingList.Count - 1

                    iTotal = m_DrawingList.Count
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList(i))
                        objPID2d = objPIDAutoApp.Application.radapplication

                        ChangelinkedBorder(objPID2d, m_DrawingList(i))
                        DeletelinkedBorder(objPID2d, m_DrawingList(i))
                        'DeleteEmbededBorder(objPID2d, m_DrawingList(i))
                        'SetXYorigin(objPID2d， m_DrawingList(i))
                    Catch ex As Exception

                        LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸未能打开")
                    End Try
                    If Not objPIDADrawing Is Nothing Then
                        Try
                            objPIDADrawing.CloseDrawing(True)
                            LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    图纸关闭成功")
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸关闭失败")
                        End Try
                    End If
                    RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                Next
            ElseIf CheckDeletelinked.Checked = False And CheckDeleteEmbeded.Checked = True Then
                For i = 0 To m_DrawingList.Count - 1

                    iTotal = m_DrawingList.Count
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList(i))
                        objPID2d = objPIDAutoApp.Application.radapplication

                        ChangelinkedBorder(objPID2d, m_DrawingList(i))
                        'DeletelinkedBorder(objPID2d, m_DrawingList(i))
                        DeleteEmbededBorder(objPID2d, m_DrawingList(i))
                        'SetXYorigin(objPID2d， m_DrawingList(i))
                    Catch ex As Exception

                        LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸未能打开")
                    End Try
                    If Not objPIDADrawing Is Nothing Then
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸关闭失败")
                        End Try
                    End If
                    RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                Next
            ElseIf CheckDeletelinked.Checked = False And CheckDeleteEmbeded.Checked = False Then
                For i = 0 To m_DrawingList.Count - 1

                    iTotal = m_DrawingList.Count
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList(i))
                        objPID2d = objPIDAutoApp.Application.radapplication

                        ChangelinkedBorder(objPID2d, m_DrawingList(i))
                        'DeletelinkedBorder(objPID2d, m_DrawingList(i))
                        'DeleteEmbededBorder(objPID2d, m_DrawingList(i))
                        'SetXYorigin(objPID2d， m_DrawingList(i))
                    Catch ex As Exception

                        LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸未能打开")
                    End Try
                    If Not objPIDADrawing Is Nothing Then
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & m_DrawingList(i) & "    Error 图纸关闭失败")
                        End Try
                    End If
                    RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                Next
            End If

        End If
        ExcuteLog(LogList)
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 100, 100, sMsg, "Finish !")
        Dim redr As DialogResult = RadMessageBox.Show("Update Border Finished！" + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If redr = DialogResult.Yes Then
            RunCMD("start " & strLogPath)    '打开log日志
        End If
        'RadMessageBox.Show("Finish!")
    End Sub
    Public Sub ChangelinkedBorder(rad2dapp As Ingr.RAD2D.Interop.RAD2D.Application, sDrawingName As String)

        Dim sOldPath As String
        Dim oNewPath As Object
        Dim index As Integer = 1
        Dim Dx As Double
        Dim Dy As Double
        oNewPath = TextNewLinkedPath.Text
        sOldPath = TXTOldPath.Text
        Dim oDocuments As Ingr.RAD2D.Interop.RAD2D.Documents = rad2dapp.Documents
        Dim oDoc As Ingr.RAD2D.Interop.RAD2D.Document
        For Each oDoc In oDocuments
            For Each objSmartFrame2d In oDoc.ActiveSheet.SmartFrames2d
                If objSmartFrame2d.IsLink Then
                    If objSmartFrame2d.LinkMoniker = sOldPath And index = 1 Then  '初次遍历到Old Path

                        Try
                            objSmartFrame2d.ChangeSource(0, oNewPath)
                            objSmartFrame2d.GetOrigin(Dx, Dy)
                            If Not Dx = 0 Or Not Dy = 0 Then
                                objSmartFrame2d.SetOrigin(0, 0)
                            End If
                            oDoc.Save()
                            index = index + 1
                            LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    更换图框成功，并且图框更新为原点")
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    Error 更换图框失败")
                        End Try
                    ElseIf objSmartFrame2d.LinkMoniker = sOldPath And index > 1 Then '非初次遍历到，会删除冗余的                                                                        '不是初次遍历到OldPath，冗余的都删掉
                        Try
                            objSmartFrame2d.Delete()
                            oDoc.Save()
                            index = index + 1
                            LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    删除同old Path相同冗余图框成功")
                        Catch ex As Exception
                            LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    Error 更换图框，同old Path相同冗余图框失败")
                        End Try
                    End If
                End If
            Next
        Next

    End Sub

    Public Sub DeletelinkedBorder（rad2dapp As Ingr.RAD2D.Interop.RAD2D.Application, sDrawingName As String）

        Dim sOldPath As String
        Dim sNewPath As String
        Dim sLayer As String = ""
        sNewPath = TextNewLinkedPath.Text
        sOldPath = TXTOldPath.Text

        Dim sLinkMoniker As String = ""
        Dim oDocuments As Ingr.RAD2D.Interop.RAD2D.Documents = rad2dapp.Documents
        Dim oDoc As Ingr.RAD2D.Interop.RAD2D.Document
        For Each oDoc In oDocuments
            For Each objSmartFrame2d In oDoc.ActiveSheet.SmartFrames2d
                If objSmartFrame2d.IsLink Then
                    sLinkMoniker = objSmartFrame2d.LinkMoniker  '如果link文件和Template中不同
                    sLayer = objSmartFrame2d.Layer
                    If sLinkMoniker <> sNewPath Then
                        If InStr(sLinkMoniker, "A1") Or InStr(sLinkMoniker, "A0") Or sLayer = "DrawingBorder" Then  '如果link的文件中含有A1或者A0字样，表明是图框，排除插如的贴图
                            Try
                                objSmartFrame2d.Delete()
                                LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    删除冗余Link图框成功")
                            Catch ex As Exception
                                LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    Error 删除冗余link图框失败")
                            End Try
                        End If
                    End If
                End If
            Next

        Next

    End Sub

    Public Sub DeleteEmbededBorder(rad2dapp As Ingr.RAD2D.Interop.RAD2D.Application, sDrawingName As String)

        Dim sEmbedMoniker As String = ""
        Dim sLayer As String = ""
        Dim oDocuments As Ingr.RAD2D.Interop.RAD2D.Documents = rad2dapp.Documents
        Dim oDoc As Ingr.RAD2D.Interop.RAD2D.Document
        For Each oDoc In oDocuments
            For Each objSmartFrame2d In oDoc.ActiveSheet.SmartFrames2d
                If objSmartFrame2d.IsLink = False Then
                    Try
                        For Each AttributeSet In objSmartFrame2d.AttributeSets
                            Debug.Print(AttributeSet.SetName)
                            If AttributeSet.SetName = "_DisplayManager" Then
                                sEmbedMoniker = AttributeSet.Item(0).GetValue().ToString()
                            End If
                            'Dim i As Integer
                            'Dim AttKey As Variable
                            'Dim AttValue As Variable
                            'For i = 0 To AttributeSet.count - 1

                            '    AttKey = AttributeSet(i)
                            '    AttValue = AttKey.GetValue().ToString()
                            'Next
                        Next

                        '            foreach(SmartFrame2d sf In _Sheet.SmartFrames2d)
                        '{
                        '    If (!sf.IsBackground) Then
                        '                                {
                        '        foreach(AttributeSet attSet In sf.AttributeSets)
                        '        {
                        '            For (Int() i = 0; i < attSet.Count; i++)
                        '            {
                        '                var AttKey = attSet[i];
                        '                var AttValue = AttKey.GetValue();
                        '            }

                        '        }
                        '    }
                        '}





                        sLayer = objSmartFrame2d.Layer
                        If InStr(sEmbedMoniker, "A1") Or InStr(sEmbedMoniker, "A0") Or sLayer = "DrawingBorder" Then  '如果嵌入的文件名称中含有A1或者A0字样，表明是图框，排除插如的贴图
                            Try
                                objSmartFrame2d.Delete()
                                LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    删除冗余嵌入图框成功")
                            Catch ex As Exception
                                LogList.Add(“Update Border“ & CONNMARK & sDrawingName & "    Error 删除冗余嵌入图框失败")
                            End Try
                        End If
                    Catch ex As Exception

                    End Try

                End If
            Next
        Next

    End Sub


    Private Sub BtnGetTempPath_Click(sender As Object, e As EventArgs) Handles BtnGetTempPath.Click

        Dim objDrawing As LMDrawing
        Dim stempName As String = ""
        Dim sTempPath As String = ""
        Dim objDoc As Ingr.RAD2D.Document
        Dim objSmartFrame2d As Ingr.RAD2D.SmartFrame2d
        Dim objSmartFrames2d As Ingr.RAD2D.SmartFrames2d
        Dim sLinkedPath As String

        DS = New LMADataSource
        Try
            Try
                initialzeSSK()
            Catch ex As Exception
                LogList.Add("Get Border Path::" & "  初始化SSK失败，请安装SSK 2016,或者手工输入模板的路径 ")
            End Try
            If Not sskApp Is Nothing Then
                SelectedDrawing()
                If m_DrawingIDList.Count > 0 Then
                    objDrawing = DS.GetDrawing(m_DrawingIDList.Item(0))
                    stempName = objDrawing.Attributes("Template").Value

                    sTempPath = GetTemplatePath(DS) & "\" & stempName
                    'sTempPath = "\\ZspiD\INGR\INGR02\P&ID Reference Data\Template Files" & "\" & stempName
                    Try
                        objDoc = sskApp.Documents.Open(sTempPath, True)
                        If Not objDoc Is Nothing Then
                            objSmartFrames2d = objDoc.ActiveSheet.SmartFrames2d
                            If CheckedLinked.IsChecked Then
                                For Each objSmartFrame2d In objSmartFrames2d
                                    If (objSmartFrame2d.IsLink) Then
                                        sLinkedPath = objSmartFrame2d.LinkMoniker
                                        TxtTempPath.Text = sLinkedPath
                                        Exit For
                                    End If
                                Next

                            ElseIf CheckedEmbeded.IsChecked Then
                                For Each objSmartFrame2d In objSmartFrames2d
                                    For Each AttributeSet In objSmartFrame2d.AttributeSets
                                        'Debug.Print(AttributeSet.SetName)
                                        If AttributeSet.SetName = "_DisplayManager" Then
                                            TxtTempPath.Text = AttributeSet.Item(0).GetValue().ToString()
                                        End If
                                    Next
                                Next


                            End If
                        End If

                    Catch ex As Exception
                        RadMessageBox.Show("无法获取模板的路径，请手工输入！")
                    End Try

                Else
                    RadMessageBox.Show("Please Select at least one Drawing")
                End If
            End If

        Catch ex As Exception
            LogList.Add("Get Border Path::" & "  ERROR Get Template Path ")
        End Try

        ReleaseCOMObjects(DS, objDrawing)
        ExcuteLog(LogList)
    End Sub

    Private Sub btnsetorigin_Click(sender As Object, e As EventArgs) Handles btnsetorigin.Click

        RadProgressBarElement2.Value1 = 0
        RadProgressBarElement2.Value2 = 0
        sMsg = "Set X Y Origin"
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 1, 100000, sMsg, "Starting")
        SelectedDrawing()  '查询出所有勾选的图纸

        RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
        Dim dr As DialogResult = RadMessageBox.Show("Do you want Set border Origin", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)

        If dr = DialogResult.Yes And m_DrawingList.Count > 0 Then
            'Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing = Nothing
            Dim i As Integer
            Dim IntCount As Integer = 0
            'Dim DrawingOpenCount As Integer = 0
            DS = New LMADataSource

            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = True
            Catch
                MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                Exit Sub

            End Try
            If Not objPIDAutoApp Is Nothing Then
                For i = 0 To m_DrawingList.Count - 1
                    iTotal = m_DrawingList.Count
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(m_DrawingList(i))
                        objPID2d = objPIDAutoApp.Application.radapplication
                        SetXYorigin(objPID2d， m_DrawingList(i))
                    Catch ex As Exception
                        LogList.Add(“Set XY origin“ & CONNMARK & m_DrawingList(i) & "    Error 图纸未能打开")
                    End Try
                    If Not objPIDADrawing Is Nothing Then
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            LogList.Add(“Set XY origin“ & CONNMARK & m_DrawingList(i) & "    Error 图纸关闭失败")
                        End Try
                    End If
                    RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                Next
            End If
        End If
        ExcuteLog(LogList)
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 100, 100, sMsg, "Finish !")
        Dim redr As DialogResult = RadMessageBox.Show("Set XY origin Finished！" + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If redr = DialogResult.Yes Then
            RunCMD("start " & strLogPath)    '打开log日志
        End If
    End Sub

    Public Sub SetXYorigin(rad2dapp As Ingr.RAD2D.Interop.RAD2D.Application， sDrawingName As String)

        Dim dX As Double = 0
        Dim dY As Double = 0
        Dim sNewPath As String
        Dim sEmbedMoniker As String
        Dim ischanged As Boolean

        dX = Trim(TextOriginX.Text) / 1000
        dY = Trim(TextOriginY.Text) / 1000
        sNewPath = TxtTempPath.Text
        ischanged = False
        Dim sLinkMoniker As String = ""
        Dim oDocuments As Ingr.RAD2D.Interop.RAD2D.Documents = rad2dapp.Documents
        Dim oDoc As Ingr.RAD2D.Interop.RAD2D.Document
        If CheckedLinked.IsChecked Then
            For Each oDoc In oDocuments
                For Each objSmartFrame2d In oDoc.ActiveSheet.SmartFrames2d
                    If objSmartFrame2d.IsLink Then
                        sLinkMoniker = objSmartFrame2d.LinkMoniker  '如果link文件和Template中不同
                        'sName = objSmartFrame2d.Name
                        If sLinkMoniker = sNewPath Then
                            Try
                                objSmartFrame2d.SetOrigin(dX, dY)
                                LogList.Add(“Set XY origin“ & CONNMARK & sDrawingName & "    更新图框位置成功")
                                ischanged = True
                                Exit Sub
                            Catch ex As Exception
                                ischanged = False
                                'LogList.Add(“Set XY origin“ & CONNMARK & sDrawingName & "    Error 更新图框位置失败")
                            End Try
                        End If
                    End If
                Next
            Next
            If ischanged = False Then  '有可能找不到Linked的图框从而失败，也有可能找到了由于其他原因无法更新
                LogList.Add(“Set XY origin“ & CONNMARK & sDrawingName & "    Error 更新图框位置失败")
            End If

        ElseIf CheckedEmbeded.IsChecked Then
            ischanged = False
            For Each oDoc In oDocuments
                For Each objSmartFrame2d In oDoc.ActiveSheet.SmartFrames2d
                    For Each AttributeSet In oDoc.ActiveSheet.SmartFrames2d.AttributeSets
                        'Debug.Print(AttributeSet.SetName)
                        If AttributeSet.SetName = "_DisplayManager" Then
                            sEmbedMoniker = AttributeSet.Item(0).GetValue().ToString()
                            If sEmbedMoniker = sNewPath Then
                                Try
                                    objSmartFrame2d.SetOrigin(dX, dY)
                                    LogList.Add(“Set XY origin“ & CONNMARK & sDrawingName & "    更新图框位置成功")
                                    ischanged = True
                                    Exit Sub
                                Catch ex As Exception
                                    ischanged = False
                                End Try
                            End If
                        End If
                    Next
                Next
            Next

            If ischanged = False Then  '有可能找不到嵌入的图框从而失败，也有可能找到了由于其他原因无法更新
                LogList.Add(“Set XY origin“ & CONNMARK & sDrawingName & "    Error 更新图框位置失败")
            End If
        End If
    End Sub

    Private Sub BtnGenerateReport_Click(sender As Object, e As EventArgs) Handles BtnGenerateReport.Click
        Dim strFileName As String
        Dim objExcel As Excel.Application

        RadProgressBarElement2.Value1 = 0
        RadProgressBarElement2.Value2 = 0

        sMsg = "Generate Border Report "
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 1, 100000, sMsg, "Starting")

        objExcel = CreateObject("Excel.Application")
        objExcel.Visible = True
        Dim xlWorkbook As Excel.Workbook
        xlWorkbook = objExcel.Workbooks.Add
        Dim xlWorksheet As Excel.Worksheet
        xlWorksheet = xlWorkbook.Worksheets("SHEET1")

        Dim Row As Long
        Row = 1


        xlWorksheet.Cells(Row, 1) = "Drawing Name"
        xlWorksheet.Cells(Row, 2) = "Is Linked"
        xlWorksheet.Cells(Row, 3) = "Link Path or Embeded File Name"
        xlWorksheet.Cells(Row, 4) = "Object Type"
        xlWorksheet.Cells(Row, 5) = "X Y Location (mm)"
        Row = Row + 1

        Dim objDrawing As LMDrawing
        Dim sDrawingPath As String = ""
        Dim objDoc As Ingr.RAD2D.Document
        Dim objSmartFrame2d As Ingr.RAD2D.SmartFrame2d
        Dim objSmartFrames2d As Ingr.RAD2D.SmartFrames2d
        Dim sLinkedPath As String
        Dim sEmbededfileName As String
        Dim i As Integer
        Dim dx As Double
        Dim dy As Double

        DS = New LMADataSource

        SelectedDrawing()
        iTotal = m_DrawingIDList.Count
        If m_DrawingIDList.Count > 0 Then
            initialzeSSK()
            For i = 0 To m_DrawingList.Count - 1
                objDrawing = DS.GetDrawing(m_DrawingIDList(i))
                sDrawingPath = GetPlantPath() & objDrawing.Attributes("Path").Value
                xlWorksheet.Cells(Row, 1) = m_DrawingList(i)
                Dim flag As Boolean = Not String.IsNullOrWhiteSpace(sDrawingPath) AndAlso File.Exists(sDrawingPath)
                If flag Then
                    Dim flag2 As Boolean = IsAnyDrawingOpened(sDrawingPath)
                    If flag2 Then
                        RadMessageBox.Show("Please close the Drawing " & m_DrawingList(i) & " then run  the tool ! ")
                        Exit Sub
                        'LogList.Add（"Border tool Generator Link border Report::" & " This drawing needs to be closed to process further" + m_DrawingList(i)）
                    Else
                        Try
                            objDoc = sskApp.Documents.Open(sDrawingPath, True)  'Add try

                            If Not objDoc Is Nothing Then
                                objSmartFrames2d = objDoc.ActiveSheet.SmartFrames2d
                                Try
                                    For Each objSmartFrame2d In objSmartFrames2d
                                        Try
                                            Dim isLink As Boolean = objSmartFrame2d.IsLink
                                            If isLink Then
                                                sLinkedPath = objSmartFrame2d.LinkMoniker
                                                xlWorksheet.Cells(Row, 2) = "True"
                                                xlWorksheet.Cells(Row, 3) = sLinkedPath
                                                xlWorksheet.Cells(Row, 4) = objSmartFrame2d.ObjectType
                                                objSmartFrame2d.GetOrigin(dx, dy)

                                                xlWorksheet.Cells(Row, 5) = Math.Round(dx * 1000) & ", " & Math.Round(dy * 1000)
                                            Else
                                                Dim isDisplayManager As Boolean = False
                                                'sEmbededfileName = objSmartFrame2d.Object.FullName
                                                For Each AttributeSet In objSmartFrame2d.AttributeSets
                                                    'Debug.Print(AttributeSet.SetName)
                                                    If AttributeSet.SetName = "_DisplayManager" Then
                                                        isDisplayManager = True
                                                        sEmbededfileName = AttributeSet.Item(0).GetValue().ToString()
                                                        xlWorksheet.Cells(Row, 2) = "False"
                                                        xlWorksheet.Cells(Row, 3) = sEmbededfileName
                                                        xlWorksheet.Cells(Row, 4) = objSmartFrame2d.ObjectType
                                                        objSmartFrame2d.GetOrigin(dx, dy)
                                                        xlWorksheet.Cells(Row, 5) = Math.Round(dx * 1000) & ", " & Math.Round(dy * 1000)
                                                        'ElseIf AttributeSet.SetName = "_SmartFrameAttributeSet" Then
                                                        '    sEmbededfileName = AttributeSet.Item(0).GetValue().ToString()
                                                        '    xlWorksheet.Cells(Row, 2) = "False"
                                                        '    xlWorksheet.Cells(Row, 3) = sEmbededfileName
                                                        '    xlWorksheet.Cells(Row, 4) = objSmartFrame2d.ObjectType
                                                    End If
                                                Next
                                                If isDisplayManager = False Then  'PID图纸上选中Embeded的对象名称为空，有可能为图纸之间复制插入的对象
                                                    xlWorksheet.Cells(Row, 2) = "False"
                                                    xlWorksheet.Cells(Row, 3) = "Embed File Name is blank"
                                                    xlWorksheet.Cells(Row, 4) = "SmartPlantPID Document"

                                                End If

                                            End If
                                            LogList.Add（"Border tool Generator Link border Report::" & "  Successfully reported linked doc source On drawing " + m_DrawingList(i)）
                                        Catch ex As Exception
                                            LogList.Add（"Border tool Generator Link border Report::" & " ERROR Falied reported linked doc source On drawing " + m_DrawingList(i)）
                                        End Try
                                        Row = Row + 1

                                        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, i + 1, iTotal, sMsg, m_DrawingList(i))
                                    Next
                                Finally
                                    Dim enumerator2 As IEnumerator(Of SmartFrame2d)
                                    If enumerator2 IsNot Nothing Then
                                        enumerator2.Dispose()
                                    End If

                                End Try
                            End If

                        Catch ex2 As Exception
                            LogList.Add（"Border tool Generator Link border Report::" & " ERROR" & ex2.Message & +m_DrawingList(i)）
                        End Try
                    End If


                Else
                    LogList.Add（"Border tool Generator Link border Report::" & "This drawing needs to be recreated to process further" & m_DrawingList(i)）
                End If
            Next
        Else
            RadMessageBox.Show("Please Select at least one Drawing")
        End If

        'strFileName = Environ("TEMP") & "\" & DS.ProjectNumber & " Border Report.xls"
        strFileName = Environ("TEMP") & "\" & DS.ProjectNumber & " Border Report"



        Dim n As Integer
        n = 0
        Try
            If IO.File.Exists(strFileName & ".xls") Then
                Do
                    n = n + 1
                    If Not IO.File.Exists(strFileName & CStr(n) & ".xls") Then Exit Do
                Loop
                objExcel.Workbooks(1).SaveAs(strFileName & CStr(n) & ".xls")
            Else
                objExcel.Workbooks(1).SaveAs(strFileName & ".xls")

            End If
        Catch ex As Exception

        End Try
        'objExcel.Workbooks(1).SaveAs(strFileName)
        ReleaseCOMObjects(DS, objDrawing)
        'xlWorkbook.Close()   '
        'objExcel.Quit()
        Call ExcuteLog(LogList)
        RefreshProcessBar(RadProgressBarElement2, RadStatusStrip2, 100, 100, sMsg, "Finish !")
        Dim redr As DialogResult = RadMessageBox.Show("Generator Link border Report Finished！" + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If redr = DialogResult.Yes Then
            RunCMD("start " & strLogPath)    '打开log日志
        End If
    End Sub


    Public Function IsAnyDrawingOpened(sFileName As String) As Boolean
        Dim text As String = String.Empty
        Dim text2 As String = "Border tool Generator Link border Report:: IsAnyDrawingOpened"
        Dim text3 As String = ""

        Dim result As Boolean
        Try
            Dim flag As Boolean = Not String.IsNullOrEmpty(sFileName)
            If flag Then
                Try
                    Dim flag2 As Boolean = IsFileInUse(sFileName)
                    Dim flag3 As Boolean = flag2
                    If flag3 Then
                        result = True
                        text3 = "Border tool Generator Link border Report:: IsAnyDrawingOpened" & "::" & “Drawing is opened!”
                        LogList.Add(text3)

                    End If
                Catch ex As Exception

                    text3 = "Border tool Generator Link border Report:: IsAnyDrawingOpened" & "::" & ex.Message
                    LogList.Add(text3)
                End Try
            End If
        Catch ex2 As Exception
            text = text2 + "::" + ex2.Message
            LogList.Add(text)
        End Try
        Return result
    End Function
    Public Function IsFileInUse(ByVal sFileName As String) As Boolean
        Dim inUse As Boolean = True
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.None)
            inUse = False
        Catch ex As Exception

        Finally
            If (fs IsNot Nothing) Then
                fs.Close()
            End If
        End Try
        Return inUse
    End Function

    Public Shared Function ReleaseCOMObjects(ByVal ParamArray objVars() As Object) As Integer
        Dim intNewRefCount As Integer = 0 ' initialize the return variable
        For Each obj As Object In objVars
            ' if obj is Nothing, then this if will "short circuit" with the AndAlso operator and IsComObject will not be evaluated
            If (Not IsNothing(obj)) AndAlso System.Runtime.InteropServices.Marshal.IsComObject(obj) Then
                intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
            End If
        Next
        Return intNewRefCount
    End Function

    Private Sub BtnCancelUpdate_Click(sender As Object, e As EventArgs) Handles BtnCancelUpdate.Click
        Exit Sub
    End Sub

    Private Sub btncancelOrigin_Click(sender As Object, e As EventArgs) Handles btncancelOrigin.Click
        Exit Sub

    End Sub

    Private Sub RadButton1_Click(sender As Object, e As EventArgs) Handles RadButton1.Click
        Exit Sub

    End Sub

    Private Sub Border_Click(sender As Object, e As EventArgs) Handles Border.Click

    End Sub

    Private Sub RadGroupBox16_Click(sender As Object, e As EventArgs) Handles RadGroupBox16.Click

    End Sub

    Private Sub RadButton2_Click(sender As Object, e As EventArgs) Handles RadButton_switch_readout_Unit.Click
        '初始化 
        RadProgressBarElement1.Value1 = 0
        RadProgressBarElement1.Value2 = 0

        sMsg = "开图切换单位，确保Save As Dwg时，正确。"
        RadMessageBox.SetThemeName(Me.RadGvidViewDralist.ThemeName)
        Dim dr As DialogResult = RadMessageBox.Show("将执行开图，以切换图纸单位为mm，确保另存为dwg时，单位正确。" + vbNewLine + "为加快速度，请先打开P&ID主程序（draft.exe)", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
        If dr = DialogResult.Yes Then
#Region "1"
            frmWaitingDialog.ShowDialogForWaiting("Please Wait")
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing

            Dim i As Integer
            Dim DwgIDs As String = ""
            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0


            SelectedDrawing()  '查询出所有勾选的图纸
            DS = New LMADataSource
            If m_DrawingList.Count > 0 Then

                For i = 0 To m_DrawingIDList.Count - 1

                    objdrawing = DS.GetDrawing(m_DrawingIDList.Item(i))
                    DwgIDs = DwgIDs + "'" + m_DrawingIDList.Item(i).ToString + "',"
                Next
                DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1)
                ReadUserAndPs_in_PID()   '获取DBtypePID
                ReadAllDBUserAndPs()

                SelectStr = ""
                SelectStr = <string>
    select t.name
    from xxxSchemaName.t_drawing t
    where t.sp_id in (xxxDWGIDS)
                        </string>.Value
                SelectStr = Replace(SelectStr, "xxxDWGIDS", DwgIDs)

                PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreate)

                'objDrawings.Collect(DS) '不要全部的图纸，只要选中的就行了
                Try
                    'On Error GoTo Failed
                    objPIDAutoApp = CreateObject("pidautomation.Application")
                    objPIDAutoApp.Visible = True   ' modifed 20220304 如果为false的话，save as PDF Title Block不会更新Revision的属性

                Catch
                    MessageBox.Show("Can't Open SPP&ID，Please check License or Whether sppid is corrupt")
                    Exit Sub

                End Try
                iTotal = dtCreate.Rows.Count

                'RadProgressBar1.Maximum = dtCreate.Rows.Count
                'RadProgressBar1.Minimum = 0

                Dim isAutoGap As Boolean = True
                Dim isopenSucess As Boolean = True

                For i = 0 To dtCreate.Rows.Count - 1

                    'DrawingOpenCount = DrawingOpenCount + 1
                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(dtCreate(i)(0))
                        Try
                            If Me.ComboBox_readout_Unit.SelectedItem.ToString = "mm" Then
                                objPIDADrawing.DistanceUnit = ReadoutUnitConstants.igunitDistanceMillimeter
                            ElseIf Me.ComboBox_readout_Unit.SelectedItem.ToString = "inch" Then
                                objPIDADrawing.DistanceUnit = ReadoutUnitConstants.igunitDistanceInch
                            End If

                        Catch ex As Exception
                            isAutoGap = False
                        End Try
                        DrawingOpenCount = DrawingOpenCount + 1
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            isopenSucess = False
                            If isAutoGap = False Then
                                LogList.Add(“开图切换单位“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开,ReadOut Unit失败，但未正常关闭")
                            Else
                                LogList.Add(“开图切换单位“ & CONNMARK & dtCreate(i)(0) & "    Error图纸打开,ReadOut Unit成功，但未正常关闭")
                            End If
                        End Try
                        If isAutoGap = True And isopenSucess = True Then
                            LogList.Add(“开图切换单位“ & CONNMARK & dtCreate(i)(0) & "    图纸打开，ReadOut Unit成功,图纸正常关闭")
                        ElseIf isopenSucess = True And isAutoGap = False Then
                            LogList.Add(“开图切换单位“ & CONNMARK & dtCreate(i)(0) & "    图纸打开,ReadOut Unit失败，图纸正常关闭")
                        End If


                    Catch ex As Exception

                        If objPIDADrawing Is Nothing Then
                            LogList.Add(“开图切换单位“ & CONNMARK & dtCreate(i)(0) & "    Error 图纸打开失败")

                        End If

                    End Try

                    'objPIDADrawing.Save()


                    IntCount = IntCount + 1
                    'RadProgressBar1.Value = IntCount
                    RefreshProcessBar(RadProgressBarElement1, RadStatusStrip1, IntCount, iTotal, sMsg, dtCreate(i)(0))
                Next
                'Sub_end(WaitingForm)
            Else
                'Sub_end(WaitingForm)
                RadMessageBox.Show("You didn't select any drawings ,Please Select Drawings !")
                Exit Sub
            End If
            Try
                '    DS.CommitTransaction()

                objPIDAutoApp.Visible = True '可能会报错，但是对结果又没影响
                objPIDAutoApp.ClearAll()
                objPIDAutoApp.Quit()
            Catch
                LogList.Add(“开图切换单位“ & CONNMARK & "    PID程序退出失败")
            End Try
            'objPIDAutoApp.Quit()
            'objPIDAutoApp = Nothing
            objPIDADrawing = Nothing
            objdrawing = Nothing
            objdrawings = Nothing
            'RadProgressBar1.Value = 0

            Call ExcuteLog(LogList)
            frmWaitingDialog.CloseDialog()
            'RadMessageBox.Show("Open Drawings Finished." + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString)
            Dim redr As DialogResult = RadMessageBox.Show("开图切换单位 Finished！" + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString + vbNewLine + "do you View log file？", "Warning", MessageBoxButtons.YesNo, RadMessageIcon.Question)
            If redr = DialogResult.Yes Then
                RunCMD("start " & strLogPath)
            End If

            'fileStreamWrite.Close()  '关闭日志
            DrawingOpenCount = Nothing
            objPID2d = Nothing
#End Region
        End If
    End Sub
    ' 以下为激活窗口所需的系统 API（放在类的末尾）
    Private Const SW_RESTORE As Integer = 9 ' 恢复窗口状态（从最小化）
    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Private Shared Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Private Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
    End Function
    ''' <summary>
    ''' 新增了一个用于辅助消除constraint report的按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadButton_ConstraintRep_Click(sender As Object, e As EventArgs) Handles RadButton_ConstraintRep.Click
        Dim Datasource = New LMADataSource
        ' 1. 被调用的 WPF exe 路径（绝对路径或相对路径）
        Dim wpfExePath As String = Path.Combine(System.Windows.Forms.Application.StartupPath,
                                                "DBCleaner",
                                                "DBCleaner.exe") ' 替换为实际路径

        ' 检查文件是否存在
        If Not File.Exists(wpfExePath) Then
            MessageBox.Show($"未找到 DBCleaner 程序：{wpfExePath}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return
        End If

        ' 2. 准备要传递的参数（多个参数用空格分隔，含空格的参数用双引号包裹）
        Dim param1 As String = Datasource.SiteNode
        Dim param2 As String = Datasource.ProjectNumber
        ' 注意：VB中双引号用两个双引号表示（"" 转义为 "）
        Dim arguments As String = $"""{param1}"" ""{param2}""" ' 用双引号包裹每个参数

        ' 3. 配置进程启动信息
        Dim startInfo As New ProcessStartInfo With {
            .FileName = wpfExePath, ' WPF 程序路径
            .Arguments = arguments, ' 传递的参数
            .UseShellExecute = False, ' 必须为 True 才能启动 GUI 程序
            .WindowStyle = ProcessWindowStyle.Normal ' 窗口显示方式
        }

        Try
            ' 2. 检查是否已有 dbcleaner.exe 进程在运行
            Dim existingProcesses() As Process = Process.GetProcessesByName("DBCleaner")
            If existingProcesses.Length > 0 Then
                ' 已存在进程： 
                ' 可选：激活已运行的窗口（使其前置显示）
                For Each proc As Process In existingProcesses
                    If Not proc.HasExited Then
                        ' 激活窗口（需要调用系统 API）
                        ShowWindow(proc.MainWindowHandle, SW_RESTORE) ' 恢复最小化窗口
                        SetForegroundWindow(proc.MainWindowHandle) ' 前置窗口
                        Exit For
                    End If
                Next
                Return ' 终止当前启动流程
            

            End If
            ' 4. 启动 WPF 程序
            Process.Start(startInfo)
            'MessageBox.Show("WPF 程序启动成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show($"启动失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class

